<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="generator" content="Asciidoctor 0.1.4">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring Security 手册</title>
    <link rel="stylesheet" type="text/css" href="index.css">
    <link rel="stylesheet" href="http://cdn.bootcss.com/font-awesome/3.2.1/css/font-awesome.css">
    <link rel="stylesheet" href="http://cdn.bootcss.com/prettify/r298/prettify.min.css">
</head>

<body class="book toc2 toc-left">
    <div id="header">
        <h1>Spring Security 手册</h1>
        <span id="author" class="author">Ben Alex</span>
        <br><span id="author2" class="author">Luke Taylor</span>
        <br><span id="author3" class="author">Rob Winch</span>
        <br>
        <span id="revnumber">version 3.2.9.RELEASE</span>
        <div id="toc" class="toc2">
            <div id="toctitle">目录</div>
            <ul class="sectlevel0">
                <li><a href="#preface">前言</a></li>
                <li><a href="#getting-started">入门</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#introduction">1. 介绍</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#what-is-acegi-security">1.1. Spring Security是什么?</a></li>
                                <li><a href="#history">1.2. 历史</a></li>
                                <li><a href="#release-numbering">1.3. 发行版本号</a></li>
                                <li><a href="#get-spring-security">1.4. 获得 Spring Security</a></li>
                            </ul>
                        </li>
                        <li><a href="#new">2. 在Spring Security 3.2中有什么新变化</a></li>
                        <li><a href="#jc">3. Java配置</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#hello-web-security-java-configuration">3.1. Hello Web Security Java 配置</a></li>
                                <li><a href="#jc-httpsecurity">3.2. HttpSecurity</a></li>
                                <li><a href="#jc-form">3.3. Java 配置和登录表单</a></li>
                                <li><a href="#authorize-requests">3.4. 授权请求</a></li>
                                <li><a href="#jc-authentication">3.5. 认证</a></li>
                                <li><a href="#multiple-httpsecurity">3.6. 多个 HttpSecurity</a></li>
                                <li><a href="#jc-method">3.7. Method Security</a></li>
                                <li><a href="#post-processing-configured-objects">3.8. Post Processing Configured Objects</a></li>
                            </ul>
                        </li>
                        <li><a href="#ns-config">4. Security 命名空间配置</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#introduction-2">4.1. 介绍</a></li>
                                <li><a href="#ns-getting-started">4.2. 入门 Security 命名空间配置</a></li>
                                <li><a href="#ns-web-advanced">4.3. 高级 Web 插件</a></li>
                                <li><a href="#ns-method-security">4.4. Method Security</a></li>
                                <li><a href="#ns-access-manager">4.5. 默认的AccessDecisionManager</a></li>
                                <li><a href="#ns-auth-manager">4.6. 身份认证管理器和命名空间</a></li>
                            </ul>
                        </li>
                        <li><a href="#sample-apps">5. 例子应用</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#tutorial-sample">5.1. Tutorial 例子</a></li>
                                <li><a href="#contacts-sample">5.2. Contacts</a></li>
                                <li><a href="#ldap-sample">5.3. LDAP 例子</a></li>
                                <li><a href="#openid-sample">5.4. OpenID 例子</a></li>
                                <li><a href="#cas-sample">5.5. CAS 例子</a></li>
                                <li><a href="#jaas-sample">5.6. JAAS 例子</a></li>
                                <li><a href="#preauth-sample">5.7. 预认证例子</a></li>
                            </ul>
                        </li>
                        <li><a href="#community">6. Spring Security 社区</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#jira">6.1. Issue Tracking</a></li>
                                <li><a href="#becoming-involved">6.2. Becoming Involved</a></li>
                                <li><a href="#further-info">6.3. Further Information</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#overall-architecture">架构和实现</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#technical-overview">1. 技术概览</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#runtime-environment">1.1. 运行环境</a></li>
                                <li><a href="#core-components">1.2. 核心组件</a></li>
                                <li><a href="#tech-intro-authentication">1.3. 身份验证</a></li>
                                <li><a href="#tech-intro-web-authentication">1.4. 在Web应用中的身份验证</a></li>
                                <li><a href="#tech-intro-access-control">1.5. 在Spring Security中访问控制 (身份验证)</a></li>
                                <li><a href="#localization">1.6. 本地化</a></li>
                            </ul>
                        </li>
                        <li><a href="#core-services">2. 核心服务</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#core-services-authentication-manager">2.1. AuthenticationManager(身份验证管理器), ProviderManager and AuthenticationProvider</a></li>
                                <li><a href="#userdetailsservice-implementations">2.2. UserDetailsService的实现</a></li>
                                <li><a href="#core-services-password-encoding">2.3. 密码加密</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#web-app-security">Web应用安全</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#security-filter-chain">1. 安全过滤器链</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#delegating-filter-proxy">1.1. DelegatingFilterProxy</a></li>
                                <li><a href="#filter-chain-proxy">1.2. FilterChainProxy</a></li>
                                <li><a href="#filter-ordering">1.3. Filter Ordering</a></li>
                                <li><a href="#request-matching">1.4. Request Matching and HttpFirewall</a></li>
                                <li><a href="#use-with-other-filter-based-frameworks">1.5. Use with other Filter-Based Frameworks</a></li>
                                <li><a href="#filter-chains-with-ns">1.6. 高级的命名空间配置</a></li>
                            </ul>
                        </li>
                        <li><a href="#core-web-filters">2. Core Security Filters</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#filter-security-interceptor">2.1. FilterSecurityInterceptor</a></li>
                                <li><a href="#exception-translation-filter">2.2. ExceptionTranslationFilter</a></li>
                                <li><a href="#security-context-persistence-filter">2.3. SecurityContextPersistenceFilter</a></li>
                                <li><a href="#form-login-filter">2.4. UsernamePasswordAuthenticationFilter</a></li>
                            </ul>
                        </li>
                        <li><a href="#servletapi">3. Servlet API 集成</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#servletapi-25">3.1. Servlet 2.5+ 集成</a></li>
                                <li><a href="#servletapi-3">3.2. Servlet 3+ 集成</a></li>
                                <li><a href="#servletapi-31">3.3. Servlet 3.1+ 集成</a></li>
                            </ul>
                        </li>
                        <li><a href="#basic">4. 基础认证和Digest(摘要)认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#basic-processing-filter">4.1. BasicAuthenticationFilter</a></li>
                                <li><a href="#digest-processing-filter">4.2. DigestAuthenticationFilter</a></li>
                            </ul>
                        </li>
                        <li><a href="#remember-me">5. Remember-Me 认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#remember-me-overview">5.1. 概览</a></li>
                                <li><a href="#remember-me-hash-token">5.2. 简单的基于哈希算法的Token方式</a></li>
                                <li><a href="#remember-me-persistent-token">5.3. 持久化 Token 方式</a></li>
                                <li><a href="#remember-me-impls">5.4. Remember-Me 的接口和实现</a></li>
                            </ul>
                        </li>
                        <li><a href="#csrf">6.跨站请求伪造 Cross Site Request Forgery (CSRF)</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#csrf-attacks">6.1. CSRF 攻击</a></li>
                                <li><a href="#synchronizer-token-pattern">6.2. Synchronizer Token Pattern</a></li>
                                <li><a href="#when-to-use-csrf-protection">6.3. 何时使用 CSRF 防护</a></li>
                                <li><a href="#csrf-using">6.4. 使用 Spring Security CSRF 防护</a></li>
                                <li><a href="#csrf-caveats">6.5. CSRF Caveats</a></li>
                                <li><a href="#overriding-defaults">6.6. 重新默认方法</a></li>
                            </ul>
                        </li>
                        <li><a href="#headers">7. Security的HTTP响应头</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#default-security-headers">7.1. Default Security Headers</a></li>
                                <li><a href="#headers-custom">7.2. Custom Headers</a></li>
                            </ul>
                        </li>
                        <li><a href="#session-mgmt">8. Session管理</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#sessionmanagementfilter">8.1. SessionManagementFilter</a></li>
                                <li><a href="#sessionauthenticationstrategy">8.2. SessionAuthenticationStrategy</a></li>
                                <li><a href="#concurrent-sessions">8.3. Concurrency Control</a></li>
                            </ul>
                        </li>
                        <li><a href="#anonymous">9. 匿名身份认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#anonymous-overview">9.1. 概览</a></li>
                                <li><a href="#anonymous-config">9.2. 配置</a></li>
                                <li><a href="#anonymous-auth-trust-resolver">9.3. AuthenticationTrustResolver</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#authorization">身份认证</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#authz-arch">1. 身份认证架构</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#authz-authorities">1.1. Authorities</a></li>
                                <li><a href="#authz-pre-invocation">1.2. Pre-Invocation Handling</a></li>
                                <li><a href="#authz-after-invocation-handling">1.3. After Invocation Handling</a></li>
                                <li><a href="#authz-hierarchical-roles">1.4. Hierarchical Roles</a></li>
                            </ul>
                        </li>
                        <li><a href="#secure-object-impls">2. 安全对象的实现</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#aop-alliance">2.1. 联合AOP (MethodInvocation) 安全拦截器</a></li>
                                <li><a href="#aspectj">2.2. AspectJ (JoinPoint) 安全拦截器</a></li>
                            </ul>
                        </li>
                        <li><a href="#el-access">3. 基于表达式的访问控制</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#overview">3.1. 概览</a></li>
                                <li><a href="#el-access-web">3.2. Web安全表达式</a></li>
                                <li><a href="#method-security-expressions">3.3. Method安全表达式</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#advanced-topics">附加话题</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#domain-acls">1. 域对象的安全Domain Object Security (ACLs)</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#domain-acls-overview">1.1. 概览</a></li>
                                <li><a href="#domain-acls-key-concepts">1.2. 关键概念</a></li>
                                <li><a href="#domain-acls-getting-started">1.3. 入门</a></li>
                            </ul>
                        </li>
                        <li><a href="#preauth">2. 预认证 Scenarios</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#pre-authentication-framework-classes">2.1. 预认证框架的类</a></li>
                                <li><a href="#concrete-implementations">2.2. 具体实现</a></li>
                            </ul>
                        </li>
                        <li><a href="#ldap">3. LDAP认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#ldap-overview">3.1. 概览</a></li>
                                <li><a href="#using-ldap-with-spring-security">3.2. 使用Spring Security的LDAP</a></li>
                                <li><a href="#ldap-server">3.3. 配置一个LDAP服务</a></li>
                                <li><a href="#implementation-classes">3.4. 实现类</a></li>
                                <li><a href="#ldap-active-directory">3.5. Active Directory Authentication</a></li>
                            </ul>
                        </li>
                        <li><a href="#taglibs">4. JSP 标签库</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#declaring-the-taglib">4.1. 定义标签库</a></li>
                                <li><a href="#the-authorize-tag">4.2. The authorize Tag</a></li>
                                <li><a href="#the-authentication-tag">4.3. The authentication Tag</a></li>
                                <li><a href="#the-accesscontrollist-tag">4.4. The accesscontrollist Tag</a></li>
                                <li><a href="#the-csrfinput-tag">4.5. The csrfInput Tag</a></li>
                                <li><a href="#the-csrfmetatags-tag">4.6. The csrfMetaTags Tag</a></li>
                            </ul>
                        </li>
                        <li><a href="#jaas">5. Java认证和授权服务(JAAS) 提供者</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#overview-2">5.1. 概览</a></li>
                                <li><a href="#jaas-abstractjaasauthenticationprovider">5.2. AbstractJaasAuthenticationProvider</a></li>
                                <li><a href="#jaas-defaultjaasauthenticationprovider">5.3. DefaultJaasAuthenticationProvider</a></li>
                                <li><a href="#jaas-jaasauthenticationprovider">5.4. JaasAuthenticationProvider</a></li>
                                <li><a href="#jaas-apiprovision">5.5. Running as a Subject</a></li>
                            </ul>
                        </li>
                        <li><a href="#cas">6. CAS 认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#cas-overview">6.1. 概览</a></li>
                                <li><a href="#cas-how-it-works">6.2. CAS是如何工作的</a></li>
                                <li><a href="#cas-client">6.3. 配置CAS的客户端</a></li>
                            </ul>
                        </li>
                        <li><a href="#x509">7. X.509 认证</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#x509-overview">7.1. 概览</a></li>
                                <li><a href="#adding-x-509-authentication-to-your-web-application">7.2. 添加 X.509 认证到你的Web应用程序中</a></li>
                                <li><a href="#x509-ssl-config">7.3. 在Tomcat中设置SSL</a></li>
                            </ul>
                        </li>
                        <li><a href="#runas">8. Run-As Authentication Replacement</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#runas-overview">8.1. 概览</a></li>
                                <li><a href="#runas-config">8.2. 配置</a></li>
                            </ul>
                        </li>
                        <li><a href="#crypto">9. Spring Security加密模块</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#spring-security-crypto-introduction">9.1. 介绍</a></li>
                                <li><a href="#spring-security-crypto-encryption">9.2. 加密器</a></li>
                                <li><a href="#spring-security-crypto-keygenerators">9.3. 主键生成器</a></li>
                                <li><a href="#spring-security-crypto-passwordencoders">9.4. 密码加密</a></li>
                            </ul>
                        </li>
                        <li><a href="#concurrency">10. 并发支持</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#delegatingsecuritycontextrunnable">10.1. DelegatingSecurityContextRunnable</a></li>
                                <li><a href="#delegatingsecuritycontextexecutor">10.2. DelegatingSecurityContextExecutor</a></li>
                                <li><a href="#spring-security-concurrency-classes">10.3. Spring Security Concurrency Classes</a></li>
                            </ul>
                        </li>
                        <li><a href="#mvc">11. Spring MVC 集成</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#mvc-enablewebmvcsecurity">11.1. @EnableWebMvcSecurity</a></li>
                                <li><a href="#mvc-authentication-principal">11.2. @AuthenticationPrincipal</a></li>
                                <li><a href="#mvc-async">11.3. Spring MVC 异步集成</a></li>
                                <li><a href="#mvc-csrf">11.4. Spring MVC和CSRF集成</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#appendix">附录</a></li>
                <li>
                    <ul class="sectlevel1">
                        <li><a href="#appendix-schema">1. Security 数据库结构</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#user-schema">1.1. User表结构</a></li>
                                <li><a href="#persistent-login-remember-me-schema">1.2. 持久化登录(记住我) 结构</a></li>
                                <li><a href="#dbschema-acl">1.3. ACL结构</a></li>
                            </ul>
                        </li>
                        <li><a href="#appendix-namespace">2. Security命名空间</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#nsa-web">2.1. Web应用程序的安全</a></li>
                                <li><a href="#nsa-authentication">2.2. 认证服务</a></li>
                                <li><a href="#nsa-method-security">2.3. Method Security</a></li>
                                <li><a href="#nsa-ldap">2.4. LDAP命名空间选项</a></li>
                            </ul>
                        </li>
                        <li><a href="#appendix-dependencies">3. Spring Security的依赖</a></li>
                        <li>
                            <ul class="sectlevel2">
                                <li><a href="#spring-security-core-2">3.1. spring-security-core</a></li>
                                <li><a href="#spring-security-remoting-2">3.2. spring-security-remoting</a></li>
                                <li><a href="#spring-security-web-2">3.3. spring-security-web</a></li>
                                <li><a href="#spring-security-ldap-2">3.4. spring-security-ldap</a></li>
                                <li><a href="#spring-security-config-2">3.5. spring-security-config</a></li>
                                <li><a href="#spring-security-acl-2">3.6. spring-security-acl</a></li>
                                <li><a href="#spring-security-cas-2">3.7. spring-security-cas</a></li>
                                <li><a href="#spring-security-openid-2">3.8. spring-security-openid</a></li>
                                <li><a href="#spring-security-taglibs">3.9. spring-security-taglibs</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
    <div id="content">
        <div id="preamble">
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Spring Security是一个有力而又可高度自定义认证和访问控制的框架。在基于Spring的安全应用方面，它是名副其实的标准。</p>
                </div>
            </div>
        </div>
        <h1 id="preface" class="sect0"><a class="anchor" href="#preface"></a>前言</h1>
        <div class="paragraph">
            <p>Spring Security提供了一个全面的安全解决方案，为基于Java EE的企业级软件应用。 当你通过探索发掘这个参考手册的时候，我们努力的为您提供一个有用而又高可配置的安全系统。</p>
        </div>
        <div class="paragraph">
            <p>安全是一个不断前进的目标，同样重要的是要采取一种全面的、系统的方法。
                在安全圈子里，我们鼓励大家采用“层次的安全”的方式, 这样每一层都可以尽可能的安全,同时连续层也提供了额外的安全。“紧缩”每一层的安全度，让你的应用程序更健壮、更安全。
                在最底层，你需要处理，如传输安全和系统识别问题，以减轻人在这方面的中间人攻击。
                接下来，您将通常利用防火墙，也许VPN或IP的安全，以确保只有授权的系统能够尝试连接。
                在企业环境中可能会部署一个DMZ（隔离区），从后端数据库和应用服务器中分离面向公众的服务器。
                您的操作系统也将扮演一个重要组成部分，解决诸如正在运行的进程作为非特权用户和最大限度地提高文件系统的安全问题。
                操作系统通常也具有自己的防火墙来配置。 希望在某些方面，你会试图防止出现拒绝服务和对系统的残忍的暴力攻击。
                入侵检测系统也是特别有用的，比如它应用于监视和响应攻击，以能够采取保护性措施，如实时的阻断违规的 TCP/IP 地址。
                转到更高层，你的Java虚拟机将有望进行配置，以尽量减少授予不同Java类型的权限，然后你的应用程序将增加其自身的问题，特定于域的安全配置。
                Moving to the higher layers, your Java Virtual Machine will hopefully be configured to minimize the permissions granted to different Java types,
                and then your application will add its own problem domain-specific security configuration.
                Spring Security 使后者的领域——应用安全，容易得多。</p>
        </div>
        <div class="paragraph">
            <p>Of course, you will need to properly address all security layers mentioned above, together with managerial factors that encompass every layer. A non-exhaustive list of such managerial factors would include security bulletin monitoring, patching, personnel vetting, audits, change control, engineering management systems, data backup, disaster recovery, performance benchmarking, load monitoring, centralised logging, incident response procedures etc.</p>
        </div>
        <div class="paragraph">
            <p>Spring Security是专注于帮助你处理企业应用安全层, 你将会发现这里有多少不同的需求，也就有多少不同的业务问题域。一个银行业务应用的需求不同于一个电子商务应用的需求。电子商务应用有着不同的需求，比如企业销售关注于自动化工具。这些定制化的需求使得应用安全更具趣味性、挑战性和价值性。</p>
        </div>
        <div class="paragraph">
            <p>请阅读<a href="#getting-started">入门</a>, 这是所有的开始。它将给你介绍框架和基于命名空间配置系统，这样你可以起步和很快的让程序跑起来。想要获得更多像，理解Spring Security是如何工作的，以及你将要用到的某些类，你应该去阅读<a href="#overall-architecture">架构和实现</a>. The remaining parts of this guide are structured in a more traditional reference style, designed to be read on an as-required basis. We`d also recommend that you read up as much as possible on application security issues in general. Spring Security is not a panacea which will solve all security issues. It is important that the application is designed with security in mind from the start. Attempting to retrofit it is not a good idea. In particular, if you are building a web application, you should be aware of the many potential vulnerabilities such as cross-site scripting, request-forgery and session-hijacking which you should be taking into account from the start. The OWASP web site (<a href="http://www.owasp.org/">http://www.owasp.org/</a>) maintains a top ten list of web application vulnerabilities as well as a lot of useful reference information.</p>
        </div>
        <div class="paragraph">
            <p>我们希望你会发觉这个指导手册是有用的, 同时我们也欢迎您的反馈和<a href="#jira">建议</a>.</p>
        </div>
        <div class="paragraph">
            <p>最后,欢迎到Spring Security<a href="#community">社区</a>.</p>
        </div>
        <h1 id="getting-started" class="sect0"><a class="anchor" href="#getting-started"></a>入门</h1>
        <div class="paragraph">
            <p>指导手册的最后部分提供了深入讨论框架的架构和实现类，假如你要做各种自定义，那么这些是需要你理解的。在这个部分, 我们将要来介绍Spring Security 3.0, 用项目历史和稍微温和的使用框架入门的印象，来做一个简短的概述。特别地,我们将要看看命名空间配置，他提供了一个相对于传统Spring bean的方式非常简单的方式来保护的应用，那样你不得不逐个地通晓所有的相关实现类。</p>
        </div>
        <div class="paragraph">
            <p>We`ll also take a look at the sample applications that are available. It`s worth trying to run these and experimenting with them a bit even before you read the later sections - you can dip back into them as your understanding of the framework increases. Please also check out the <a href="http://static.springsource.org/spring-security/site/index.html">project website</a> as it has useful information on building the project, plus links to articles, videos and tutorials.</p>
        </div>
        <div class="sect1">
            <h2 id="introduction"><a class="anchor" href="#introduction"></a>1. 介绍</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="what-is-acegi-security"><a class="anchor" href="#what-is-acegi-security"></a>1.1. Spring Security是什么?</h3>
                    <div class="paragraph">
                        <p>Spring Security为基于J2EE企业应用软件提供了全面安全服务。特别是使用领先的J2EE解决方案-spring框架开发的企业软件项目。 如果你没有使用Spring开发企业软件，我们热情的推荐你仔细研究一下。-尤其是依赖注入原理-将帮助你更快的掌握Spring Security。</p>
                    </div>
                    <div class="paragraph">
                        <p>人们使用Spring Security有很多种原因， 不过通常吸引他们的是在J2EE Servlet规范或EJB规范中找不到典型企业应用场景的解决方案。 提到这些规范， 特别要指出的是它们不能在WAR或EAR级别进行移植。 这样， 如果你更换服务器环境，就要， 在新的目标环境进行大量的工作， 对你的应用系统进行重新配置安全。使用SpringSecurity解决了这些问题，也为你提供了很多有用的，可定制的其他安全特性。</p>
                    </div>
                    <div class="paragraph">
                        <p>你可能知道，安全包括两个主要操作， “认证”和“验证”（或访问控制）。 这就是 SpringSecurity面向的两个主要方向。 “认证” 是为用户建立一个他所声明的主体的过程， （ “主体”一般是指用户，设备或可以在你系统中执行行动的其他系统）。 “验证”指的一个用户能否在你的应用中执行某个操作。在到达授权判断之前，身份的主体已经由身份验证过程建立了。这些概念是通用的，不是Spring Security特有的。</p>
                    </div>
                    <div class="paragraph">
                        <p>在认证级别, Spring Security 支持一个宽广的认证模型。在大多数这些认证模块中，不是提供了第三方，就是相关标准制定者开发的，比如  Internet Engineering Task Force。 另外, Spring Security 提供了属于自己的认证插件。特别要说明的，, Spring Security currently supports authentication integration with all of these technologies:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>HTTP BASIC authentication headers (an IETF RFC-based standard)</p>
                            </li>
                            <li>
                                <p>HTTP Digest authentication headers (an IETF RFC-based standard)</p>
                            </li>
                            <li>
                                <p>HTTP X.509 client certificate exchange (an IETF RFC-based standard)</p>
                            </li>
                            <li>
                                <p>LDAP (a very common approach to cross-platform authentication needs, especially in large environments)</p>
                            </li>
                            <li>
                                <p>Form-based authentication (为简单用户界面所需要)</p>
                            </li>
                            <li>
                                <p>OpenID authentication</p>
                            </li>
                            <li>
                                <p>Authentication based on pre-established request headers (such as Computer Associates Siteminder)</p>
                            </li>
                            <li>
                                <p>JA-SIG Central Authentication Service (也被称为 CAS，这是一个流行的开源单点登录系统)</p>
                            </li>
                            <li>
                                <p>Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (一个 Spring远程调用协议)</p>
                            </li>
                            <li>
                                <p>Automatic "remember-me" authentication (这样你可以设置一段时间， 避免在一段时
间内还需要重新验证)</p>
                            </li>
                            <li>
                                <p>Anonymous authentication (允许任何调用，自动假设一个特定的安全主体)</p>
                            </li>
                            <li>
                                <p>Run-as authentication (这在一个会话内使用不同安全身份的时候是非常有用的)</p>
                            </li>
                            <li>
                                <p>Java Authentication and Authorization Service (JAAS)</p>
                            </li>
                            <li>
                                <p>JEE container autentication (so you can still use Container Managed Authentication if desired)</p>
                            </li>
                            <li>
                                <p>Kerberos</p>
                            </li>
                            <li>
                                <p>Java Open Source Single Sign On (JOSSO) *</p>
                            </li>
                            <li>
                                <p>OpenNMS Network Management Platform *</p>
                            </li>
                            <li>
                                <p>AppFuse *</p>
                            </li>
                            <li>
                                <p>AndroMDA *</p>
                            </li>
                            <li>
                                <p>Mule ESB *</p>
                            </li>
                            <li>
                                <p>Direct Web Request (DWR) *</p>
                            </li>
                            <li>
                                <p>Grails *</p>
                            </li>
                            <li>
                                <p>Tapestry *</p>
                            </li>
                            <li>
                                <p>JTrac *</p>
                            </li>
                            <li>
                                <p>Jasypt *</p>
                            </li>
                            <li>
                                <p>Roller *</p>
                            </li>
                            <li>
                                <p>Elastic Path *</p>
                            </li>
                            <li>
                                <p>Atlassian Crowd *</p>
                            </li>
                            <li>
                                <p>Your own authentication systems (see below)</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>(* 表示来自第三方提供)</p>
                    </div>
                    <div class="paragraph">
                        <p>许多独立软件供应商(ISVs) adopt Spring Security because of this significant choice of flexible authentication models. Doing so allows them to quickly integrate their solutions with whatever their end clients need, without undertaking a lot of engineering or requiring the client to change their environment. If none of the above authentication mechanisms suit your needs, Spring Security is an open platform and it is quite simple to write your own authentication mechanism. Many corporate users of Spring Security need to integrate with "legacy" systems that don`t follow any particular security standards, and Spring Security is happy to "play nicely" with such systems.</p>
                    </div>
                    <div class="paragraph">
                        <p>Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest - authorizing web requests, authorizing whether methods can be invoked, and authorizing access to individual domain object instances. To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively. Spring Security provides deep capabilities in all of these important areas, which we`ll explore later in this reference guide.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="history"><a class="anchor" href="#history"></a>1.2. 历史</h3>
                    <div class="paragraph">
                        <p>Spring Security 开始于2003年年底， ““spring的acegi安全系统”。 起因是 Spring开发者邮件列表中的一个问题，有人提问是否考虑提供一个基于 spring的安全实现。 在当时 Spring的社区相对较小（尤其是和今天的规模比！），其实Spring本身是从2003年初才作为一个sourceforge的项目出现的。 对这个问题的回应是， 这的确是一个值得研究的领域，虽然限于时间问题阻碍了对它的继续研究。</p>
                    </div>
                    <div class="paragraph">
                        <p>带着这种思想， 一个简单的Security实现建立起来了， 但没有发布。几周之后， spring社区的其他成员询问安全问题，代码就被提供给了他们。随后又有人请求，在2004年一月左右，有20人在使用这些代码。另外一些人加入到这些先行者中来，并建议在sourceforge上建立一个项目，项目在2004年3月正式建立起来。</p>
                    </div>
                    <div class="paragraph">
                        <p>在早期, 项目本身并没有属于自己的认证模块。认证过程都是依赖容器管理安全的， 而acegi则注重授权。这在一开始是合适的，但随着越来越多用户要求提供额外的容器支持，基于容器认证的限制就显现出来了。还有一个有关的问题，向容器的 classpath中添加新 jar，常常让最终用户感到困惑，又容易出现配置错误。</p>
                    </div>
                    <div class="paragraph">
                        <p>随后acegi加入了认证服务。大约一年后， acegi成为spring的官方子项目。经过了两年半在许多生产软件项目中的活跃使用和数以万计的改善和社区的贡献，1.0.0最终版本发布于2006年5月。</p>
                    </div>
                    <div class="paragraph">
                        <p>Acegi在2007年年底，正式成为spring组合项目，被更名为“Spring Security”。</p>
                    </div>
                    <div class="paragraph">
                        <p>现在， Spring Security成为了一个强大而又活跃的开源社区。在支持论坛上有数以千计的关于Spring Security的消息。有一个积极的核心开发团队专职开发，一个积极的社区定期共享补丁并支持他们的同伴。</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="release-numbering"><a class="anchor" href="#release-numbering"></a>1.3.发行版本号</h3>
                    <div class="paragraph">
                        <p>了解 spring Security发行版本号是非常有用的。它可以帮助你判断升级到新的版本是否需要花费很大的精力。
                            版本号是一个包含三个整数的组合： 主要版本号.次要版本号.补丁。 主版本的意图是不兼容的、大规模的升级API；
                            次要版本号在源代码和二进制要与老版本保持兼容，认为也许有些设计上的改变和不兼容性更新；
                            补丁级别应该是从前向后的完全兼容，并有可能修复bug和缺陷。</p>
                    </div>
                    <div class="paragraph">
                        <p>你受更改影响的程度将取决于你的代码是否紧密集成。The extent to which you are affected by changes will depend on how tightly integrated your code is.
                            If you are doing a lot of customization you are more likely to be affected than if you are using a simple namespace configuration.</p>
                    </div>
                    <div class="paragraph">
                        <p>每当你升级一个新版本前，你都必须要完整的测试你的应用。</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="get-spring-security"><a class="anchor" href="#get-spring-security"></a>1.4. 获得 Spring Security</h3>
                    <div class="paragraph">
                        <p>你有几种方式可以获取Spring Security。你可以从<a href="http://spring.io/spring-security">Spring Security</a>主页下载中分发包,
                            也可以从Maven中央仓库（或者为了snapshot版和milestone版本到SpringSource Maven仓库）下载单个jar文件，
                            又或许，你自己可以通过源码来构建项目。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="maven"><a class="anchor" href="#maven"></a>1.4.1. Usage with Maven</h4>
                        <div class="paragraph">
                            <p>一个最小的Spring Security Maven依赖集合，一般像下面这样:</p>
                        </div>
                        <div class="listingblock">
                            <div class="title">pom.xml</div>
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;dependencies&gt;
  &lt;!-- ... other dependency elements ... --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
    &lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
    &lt;version&gt;3.2.9.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
    &lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
    &lt;version&gt;3.2.9.RELEASE&lt;/version&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>如果你要使用额外插件比如 LDAP, OpenID, 等等。 你还需要包括对应的<a href="#modules">项目模块</a>。</p>
                        </div>
                        <div class="sect4">
                            <h5 id="maven-repositories"><a class="anchor" href="#maven-repositories"></a>Maven 仓库</h5>
                            <div class="paragraph">
                                <p>All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom.</p>
                            </div>
                            <div class="paragraph">
                                <p>如果你要使用快照版本，你就需要确保你有像下面这样加入了Spring快照仓库：</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">pom.xml</div>
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;repositories&gt;
  &lt;!-- ... possibly other repository elements ... --&gt;
  &lt;repository&gt;
    &lt;id&gt;spring-snapshot&lt;/id&gt;
    &lt;name&gt;Spring Snapshot Repository&lt;/name&gt;
    &lt;url&gt;http://repo.springsource.org/snapshot&lt;/url&gt;
  &lt;/repository&gt;
&lt;/repositories&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>如果你要使用里程牌版或者发布候选版，你就需要确保你有像下面这样加入了Spring里程牌仓库：</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">pom.xml</div>
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;repositories&gt;
  &lt;!-- ... possibly other repository elements ... --&gt;
  &lt;repository&gt;
    &lt;id&gt;spring-milestone&lt;/id&gt;
    &lt;name&gt;Spring Milestone Repository&lt;/name&gt;
    &lt;url&gt;http://repo.springsource.org/milestone&lt;/url&gt;
  &lt;/repository&gt;
&lt;/repositories&gt;</code></pre>
                                </div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="maven-bom"><a class="anchor" href="#maven-bom"></a>使用Spring4和Maven</h5>
                            <div class="paragraph">
                                <p>Spring Security不但针对Spring Framework 3.2.13.RELEASE进行构建, 同时也在Spring Framework 4.1.6.RELEASE上进行构建。这意味着你可以同时使用Spring Security 3.2.9.RELEASE和Spring Framework 4.1.6.RELEASE。很多用户可能出现一个问题，那就是Spring Security用Spring Framework 3.2.13.RELEASE来解决依赖关系时，会引发各种各样奇怪的classpath问题。</p>
                            </div>
                            <div class="paragraph">
                                <p>一种龌蹉的方式可以规避这个问题， 那就是要包含所有的Spring Framework 模块到你的<a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management">&lt;dependencyManagement&gt;</a>地方。还有一个替代选择的方式是，包含<code>spring-framework-bom</code> 到你的 <code>&lt;dependencyManagement&gt;</code> section of your <code>pom.xml</code> as shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">pom.xml</div>
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;dependencyManagement&gt;
    &lt;dependencies&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-framework-bom&lt;/artifactId&gt;
        &lt;version&gt;4.1.6.RELEASE&lt;/version&gt;
        &lt;type&gt;pom&lt;/type&gt;
        &lt;scope&gt;import&lt;/scope&gt;
      &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>这将确保所有关于Spring Security的传递依赖都使用Spring 4.1.6.RELEASE模块。</p>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            This approach uses Maven`s "bill of materials" (BOM) concept and is only available in Maven 2.0.9+. For additional details about how dependencies are resolved refer to <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html">Maven`s Introduction to the Dependency Mechanism documentation</a>.
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="gradle"><a class="anchor" href="#gradle"></a>1.4.2. Gradle</h4>
                        <div class="paragraph">
                            <p>A minimal Spring Security Gradle set of dependencies typically looks like the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="title">build.gradle</div>
                            <div class="content">
                                <pre class="prettyprint groovy language-groovy"><code>dependencies {
    compile 'org.springframework.security:spring-security-web:3.2.9.RELEASE'
    compile 'org.springframework.security:spring-security-config:3.2.9.RELEASE'
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>如果你打算使用附加插件，像LDAP, OpenID等等。 你还是需要加入恰当的<a href="#modules">项目模块</a>。</p>
                        </div>
                        <div class="sect4">
                            <h5 id="gradle-repositories"><a class="anchor" href="#gradle-repositories"></a>Gradle Repositories</h5>
                            <div class="paragraph">
                                <p>All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases.</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">build.gradle</div>
                                <div class="content">
                                    <pre class="prettyprint groovy language-groovy"><code>repositories {
    mavenCentral()
}</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>如果你打算使用快照版本，你需要确认你有像下面那样定义了Spring快照仓库：</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">build.gradle</div>
                                <div class="content">
                                    <pre class="prettyprint groovy language-groovy"><code>repositories {
    maven { url 'https://repo.spring.io/snapshot' }
}</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">build.gradle</div>
                                <div class="content">
                                    <pre class="prettyprint groovy language-groovy"><code>repositories {
    maven { url 'https://repo.spring.io/milestone' }
}</code></pre>
                                </div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="gradle-resolutionStrategy"><a class="anchor" href="#gradle-resolutionStrategy"></a>Using Spring 4 and Gradle</h5>
                            <div class="paragraph">
                                <p>By default Gradle will use the newest version when resolving transitive versions. This means that often times no additional work is necessary when running Spring Security 3.2.9.RELEASE with Spring Framework 4.1.6.RELEASE. However, at times there can be issues that come up so it is best to mitigate this using <a href="http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html">Gradle`s ResolutionStrategy</a> as shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="title">build.gradle</div>
                                <div class="content">
                                    <pre class="prettyprint groovy language-groovy"><code>configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details -&gt;
        if (details.requested.group == 'org.springframework') {
            details.useVersion '4.1.6.RELEASE'
        }
    }
}</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>这样将确保所有的Spring Security传递依赖都是使用Spring 4.1.6.RELEASE模块。</p>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            This example uses Gradle 1.9, but may need modifications to work in future versions of Gradle since this is an incubating feature within Gradle.
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="modules"><a class="anchor" href="#modules"></a>1.4.3. 项目模块</h4>
                        <div class="paragraph">
                            <p>在Spring Security 3.0中, 基础代码被分割成子jar，这样更加清晰的区分不同的功能和第三方依赖。如果你使用Maven构建项目，那么下面模块需要你添加到<code>pom.xml</code>。即便你不使用Maven，我们建议你参考<code>pom.xml</code>文件来了解第三方依赖和版本的思路。此外, 有一个好的想法来测试库，那就是把它们包含到例子项目中去。</p>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-core"><a class="anchor" href="#spring-security-core"></a>Core - spring-security-core.jar</h5>
                            <div class="paragraph">
                                <p>包含了核心认证和权限控制类和接口， 运程支持和基本供应API。使用Spring Security所必须的。支持单独运行的应用， 远程客户端，方法（服务层）安全和JDBC用户供应。包含顶级包：</p>
                            </div>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><code>org.springframework.security.core</code></p>
                                    </li>
                                    <li>
                                        <p><code>org.springframework.security.access</code></p>
                                    </li>
                                    <li>
                                        <p><code>org.springframework.security.authentication</code></p>
                                    </li>
                                    <li>
                                        <p><code>org.springframework.security.provisioning</code></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-remoting"><a class="anchor" href="#spring-security-remoting"></a>Remoting - spring-security-remoting.jar</h5>
                            <div class="paragraph">
                                <p>提供了与Spring Remoting的集成。除非你要使用Spring Remoting写一个远程客户端，你是不会需要的。主包是<code>org.springframework.security.remoting</code>。</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-web"><a class="anchor" href="#spring-security-web"></a>Web - spring-security-web.jar</h5>
                            <div class="paragraph">
                                <p>包含过滤器和对应的web安全架构代码。任何需要依赖servlet API的。 你将需要它，如果你需要 Spring Security Web 认证服务和基于 URL 的权限控制。 主包是<code>org.springframework.security.web</code>。</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-config"><a class="anchor" href="#spring-security-config"></a>Config - spring-security-config.jar</h5>
                            <div class="paragraph">
                                <p>包含安全命名控制解析代码（ 因此我们不能直接把它用在你的应用中）。 你需要它，如果使用了Spring Security XML 命名控制来进行配置。主包是<code>org.springframework.security.config</code>。
                                    None of the classes are intended for direct use in an application.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-ldap"><a class="anchor" href="#spring-security-ldap"></a>LDAP - spring-security-ldap.jar</h5>
                            <div class="paragraph">
                                <p>LDAP认证和实现代码，如果你需要使用LDAP认证或管理LDAP用户实体就是必须的。 顶级包是<code>org.springframework.security.ldap</code>。</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-acl"><a class="anchor" href="#spring-security-acl"></a>ACL - spring-security-acl.jar</h5>
                            <div class="paragraph">
                                <p>处理领域对象ACL实现。 用来提供安全给特定的领域对象实例， 在你的应用中。 顶级包是 <code>org.springframework.security.acls</code>.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-cas"><a class="anchor" href="#spring-security-cas"></a>CAS - spring-security-cas.jar</h5>
                            <div class="paragraph">
                                <p>Spring Security的CAS客户端集成。如果你希望使用Spring Security web认证整合一个CAS单点登录服务器。顶级包是<code>org.springframework.security.cas</code>.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="spring-security-openid"><a class="anchor" href="#spring-security-openid"></a>OpenID - spring-security-openid.jar</h5>
                            <div class="paragraph">
                                <p>OpenID web authentication support. Used to authenticate users against an external OpenID server. <code>org.springframework.security.openid</code>. Requires OpenID4Java.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="get-source"><a class="anchor" href="#get-source"></a>1.4.4. 检出源代码</h4>
                        <div class="paragraph">
                            <p>由于Spring Security是一个开源项目,我们强力鼓励你使用git检出源代码。这个将给你全部权限来访问所有的例子应用，同时你可以容易地构建最新版本的项目。
                                在调试方面，获取项目源码也是一种巨大帮助。异常堆栈信息不再是模糊不清的黑盒问题，你是可以直接定位到引起问题那行代码，找出那里发生了什么事情。</p>
                        </div>
                        <div class="paragraph">
                            <p>获得项目的源代码，使用下面git命令：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint txt language-txt"><code>git clone https://github.com/spring-projects/spring-security.git</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>这个将给你，在本地机器上访问全部的项目历史（包括所有的发布版和分支版）。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="new"><a class="anchor" href="#new"></a>2. What`s new in Spring Security 3.2</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>There are <a href="https://jira.springsource.org/issues/?jql=project%20%3D%20SEC%20AND%20fixVersion%20in%20(%223.2.0.RC2%22%2C%20%223.2.0%22%2C%20%223.2.0.RC1%22%2C%20%223.2.0.M2%22%2C%20%223.2.0.M1%22)%20ORDER%20BY%20priority%20DESC%2C%20issuetype%20ASC%2C%20key%20DESC">150+ tickets resolved</a> with the Spring Security 3.2 release. Below are the highlights of the new features found in Spring Security 3.2.</p>
                </div>
                <div class="ulist">
                    <ul>
                        <li>
                            <p><a href="#jc">Java 配置支持</a></p>
                        </li>
                        <li>
                            <p><a href="#csrf">Cross Site Request Forgery (CSRF) 防护</a></p>
                        </li>
                        <li>
                            <p><a href="#headers-frame-options">Click Jacking 防护</a></p>
                        </li>
                        <li>
                            <p><a href="#headers">Security HTTP Response Headers</a></p>
                        </li>
                        <li>
                            <p>可选 <a href="#mvc">Spring MVC</a> 集成</p>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p>Automatic Resolving <code>Authentication.getPrincipal()</code> with <a href="#mvc-authentication-principal">@AuthenticationPrincipal</a></p>
                                    </li>
                                    <li>
                                        <p>自动化<a href="#mvc-async">Spring MVC 异步集成</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#mvc-csrf">Spring MVC 和 CSRF的集成</a></p>
                                    </li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <p><a href="#concurrency">并发支持</a></p>
                        </li>
                        <li>
                            <p><a href="#servletapi-3">Servlet 3+ 集成</a> 和 <a href="#servletapi-31">Servlet 3.1+ 集成</a></p>
                        </li>
                        <li>
                            <p>拓展了<a href="#el-pre-post-annotations-arguments">方法参数名解析</a>，使之能帮助基于方法的安全</p>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p>支持标准JDK 8 反射</p>
                                    </li>
                                    <li>
                                        <p>支持基于注解的解析</p>
                                    </li>
                                    <li>
                                        <p>能够在接口中解析参数名</p>
                                    </li>
                                    <li>
                                        <p>自动集成Spring Data的 <code>@Param</code>标签</p>
                                    </li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <p>增加<code>RequestMatcher</code>的实现</p>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="http://docs.spring.io/spring-security/site/docs/3.2.x-SNAPSHOT/apidocs/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.html">MediaTypeRequestMatcher</a> - allows matching requests using content negotiation.</p>
                                    </li>
                                    <li>
                                        <p><code>OrRequestMatcher</code> - allows passing in multiple RequestMatcher instances into the contructor. If a single one returns true, then the result is true.</p>
                                    </li>
                                    <li>
                                        <p><code>AndRequestMatcher</code> - allows passing in multiple RequestMatcher instances into the contructor. If a all of them return true, then the result is true.</p>
                                    </li>
                                    <li>
                                        <p><code>NegatedRequestMatcher</code> - allows padding in a RequestMatcher instance. If the result of the delegate is false, the result is true.</p>
                                    </li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <p><code>DebugFilter</code>现在支持输出请求头</p>
                        </li>
                        <li>
                            <p>Documentation</p>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p>Started creating task focussed <a href="http://docs.spring.io/spring-security/site/docs/3.2.x-SNAPSHOT/guides/">guides</a></p>
                                    </li>
                                    <li>
                                        <p>10+ <a href="https://github.com/spring-projects/spring-security/tree/master/samples">Spring Security Samples</a> added</p>
                                    </li>
                                    <li>
                                        <p>Converted all documentation to <a href="http://asciidoctor.org/">Asciidoctor</a></p>
                                    </li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <p>Sonar integration for the build</p>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="jc"><a class="anchor" href="#jc"></a>3. Java 代码配置</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>General support for <a href="http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java">Java Configuration</a> was added to Spring framework in Spring 3.1. Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.</p>
                </div>
                <div class="paragraph">
                    <p>If you are familiar with the <a href="#ns-config">Security Namespace Configuration</a> then you should find quite a few similarities between it and the Security Java Configuration support.</p>
                </div>
                <div class="admonitionblock note">
                    <table>
                        <tr>
                            <td class="icon">
                                <i class="icon-note" title="Note"></i>
                            </td>
                            <td class="content">
                                Spring Security provides <a href="https://github.com/spring-projects/spring-security/tree/master/samples">lots of sample applications</a> that end in <code>-jc</code> which demonstrate the use of Spring Security Java Configuration.
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="hello-web-security-java-configuration"><a class="anchor" href="#hello-web-security-java-configuration"></a>3.1. Hello Web Security Java 配置</h3>
                    <div class="paragraph">
                        <p>第一步就是创建一个我们的Spring Security Java 配置。配置创建一个被称作<code>springSecurityFilterChain</code>的Servlet Filter，它是负责在你的应用中所有的安全（保护应用的URL，验证提交的用户名和密码以及重定向到登录表单，等等）。你可以找到像下面这样一个关于Spring Security Java配置最基础的例子:</p>
                    </div>
                    <div id="jc-hello-wsca" class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}</code></pre>
                        </div>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    名为“configureGlobal”的方法不是关键。
                                    然而，唯有在类中配置了AuthenticationManagerBuilder，而且这个类要被注解了<code>@EnableWebSecurity</code>，<code>@EnableWebMvcSecurity</code>，<code>@EnableGlobalMethodSecurity</code>，或者<code>@EnableGlobalAuthentication</code>，才是关键。其它做法会产生无法预料的结果。
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="paragraph">
                        <p>这真的不是很多关于这种配置的,但它确实又有很多。 你可以找从下面找插件详情：</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>在你的应用中每一个URL必须经过认证</p>
                            </li>
                            <li>
                                <p>为你生成一个登录表单</p>
                            </li>
                            <li>
                                <p>在基于表单的认证中，允许用户的<strong>用户名</strong> <em>user</em>和<strong>密码</strong> <em>password</em>通过认证</p>
                            </li>
                            <li>
                                <p>允许用户退出系统</p>
                            </li>
                            <li>
                                <p><a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF 攻击</a>预防</p>
                            </li>
                            <li>
                                <p><a href="http://en.wikipedia.org/wiki/Session_fixation">固定Session</a>保护</p>
                            </li>
                            <li>
                                <p>Security Header 集成</p>
                                <div class="ulist">
                                    <ul>
                                        <li>
                                            <p>为保护请求的<a href="http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security">HTTP Strict Transport Security</a></p>
                                        </li>
                                        <li>
                                            <p><a href="http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx">X-Content-Type-Options</a> 集成</p>
                                        </li>
                                        <li>
                                            <p>缓存控制(可以在后面通过你的应用重写，来允许缓存你的静态资源文件)</p>
                                        </li>
                                        <li>
                                            <p><a href="http://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx">X-XSS-Protection</a>集成</p>
                                        </li>
                                        <li>
                                            <p>X-Frame-Options integration to help prevent <a href="http://en.wikipedia.org/wiki/Clickjacking">Click jacking</a></p>
                                        </li>
                                    </ul>
                                </div>
                            </li>
                            <li>
                                <p>以下使Servlet API集成的方法</p>
                                <div class="ulist">
                                    <ul>
                                        <li>
                                            <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()">HttpServletRequest#getRemoteUser()</a></p>
                                        </li>
                                        <li>
                                            <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()">HttpServletRequest.html#getUserPrincipal()</a></p>
                                        </li>
                                        <li>
                                            <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)">HttpServletRequest.html#isUserInRole(java.lang.String)</a></p>
                                        </li>
                                        <li>
                                            <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)">HttpServletRequest.html#login(java.lang.String, java.lang.String)</a></p>
                                        </li>
                                        <li>
                                            <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()">HttpServletRequest.html#logout()</a></p>
                                        </li>
                                    </ul>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div class="sect3">
                        <h4 id="abstractsecuritywebapplicationinitializer"><a class="anchor" href="#abstractsecuritywebapplicationinitializer"></a>3.1.1. AbstractSecurityWebApplicationInitializer</h4>
                        <div class="paragraph">
                            <p>下一步来注册<code>springSecurityFilterChain</code>到war中。这样，在一个Servlet 3.0+环境中，带有<a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config">
                                Spring`s WebApplicationInitializer 支持</a>的Java配置就可以运行了。
                                不出意外的话，Spring Security提供一个基础类<code>AbstractSecurityWebApplicationInitializer</code>，
                                它将确保<code>springSecurityFilterChain</code>为你得到注册。
                                在这种方式中，我们可以使用<code>AbstractSecurityWebApplicationInitializer</code>来区别处理的依赖，
                                无论我们已经使用Spring或者Spring Security， 还是Spring Security在我们的项目中仅仅只是一个Spring的组件。
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><a href="#abstractsecuritywebapplicationinitializer-without-existing-spring">AbstractSecurityWebApplicationInitializer without Existing Spring</a> - 使用这儿的说明，如果你已经打算不使用Spring。</p>
                                </li>
                                <li>
                                    <p><a href="#abstractsecuritywebapplicationinitializer-with-spring-mvc">AbstractSecurityWebApplicationInitializer with Spring MVC</a> - 使用这儿的说明，如果你已经在使用Spring了。</p>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="abstractsecuritywebapplicationinitializer-without-existing-spring"><a class="anchor" href="#abstractsecuritywebapplicationinitializer-without-existing-spring"></a>3.1.2. AbstractSecurityWebApplicationInitializer without Existing Spring</h4>
                        <div class="paragraph">
                            <p>如果你不打算使用Spring或者Spring MVC，你将需要传入<code>SecurityConfig</code>到父类中来确保配置启动。你可以从下面找到一个例子：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p><code>SecurityWebApplicationInitializer</code>将要做下面事情：</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p>在你的应用中，为每一个URL自动地注册springSecurityFilterChain Filter</p>
                                </li>
                                <li>
                                    <p>添加一个上下文加载监听器ContextLoaderListener，让它加载<a href="#jc-hello-wsca">SecurityConfig</a>。</p>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="abstractsecuritywebapplicationinitializer-with-spring-mvc"><a class="anchor" href="#abstractsecuritywebapplicationinitializer-with-spring-mvc"></a>3.1.3. AbstractSecurityWebApplicationInitializer with Spring MVC</h4>
                        <div class="paragraph">
                            <p>如果在我们的应用中我们已经在别处使用了Spring，我们可能已经有一个<code>WebApplicationInitializer</code>，它将加载我们的Spring配置。
                                如果我们使用前面的配置，我们将要返回一个错误。取而代之，我应该同已经存在的<code>ApplicationContext</code>来注册。
                                举个例子，如果我们在使用Spring MVC，那么我们的<code>SecurityWebApplicationInitializer</code>应该看起来像下面这样：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
      extends AbstractSecurityWebApplicationInitializer {

}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>这样在你的应用中将简单，只有为每一个URL注册springSecurityFilterChain Filter的时候。
                                在那之后，我们将要确保<code>SecurityConfig</code>加载到我们已经存在的ApplicationInitializer中去。
                                举个例子，如果我们正在使用Spring MVC，它将要添加到<code>getRootConfigClasses()</code>。</p>
                        </div>
                        <div id="message-web-application-inititializer-java" class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public class MvcWebApplicationInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class&lt;?&gt;[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    // ... other overrides ...
}</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jc-httpsecurity"><a class="anchor" href="#jc-httpsecurity"></a>3.2. HttpSecurity</h3>
                    <div class="paragraph">
                        <p>到现在为止，我们<a href="#jc-hello-wsca">SecurityConfig</a>仅仅只包含了关于如何认证我们用户的信息。
                            Spring Security如何知道我们想要所有用户都要被经过认证？
                            Spring Security如何知道我们想要支持基于表单的认证？
                            这个答案就是，<code>WebSecurityConfigurerAdapter</code>提供了一个默认配置，到<code>configure(HttpSecurity http)</code>方法中，如下所示：
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .httpBasic();
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>在上面默认配置中：</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>确保任何请求到我们应用的，都是需要用户经过认证过了的</p>
                            </li>
                            <li>
                                <p>允许用户通过基于表单的认证方式登录</p>
                            </li>
                            <li>
                                <p>允许用户通过HTTP基本认证方式认证</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>你会注意到，这个配置相比xml命名空间配置相当的简单：</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http use-expressions="true"&gt;
    &lt;intercept-url pattern="/**" access="authenticated"/&gt;
    &lt;form-login /&gt;
    &lt;http-basic /&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Java配置中，使用<code>and()</code>的方法等价于表示一个XML标签，这样允许我们继续配置父级。
                            如果你阅读代码，这也是有意义的。 我想要配置授权了的请求、配置登录表单以及配置基础HTTP认证。
                    </div>
                    <div class="paragraph">
                        <p>无论如何，Java配置有不同的默认URL和参数。带着这种想法来创建自定义登录页。结果是，我们的URL更加具有RESTful风格。
                            另外，我们使用Spring Security来帮助我们阻止<a href="https://www.owasp.org/index.php/Information_Leak_(information_disclosure)">信息泄露（information leaks）</a>，并不是那么的明显。 举个例子：</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>GET /login 渲染登录页面，替换/spring_security_login</p>
                            </li>
                            <li>
                                <p>POST /login 认证用户，替换/j_spring_security_check</p>
                            </li>
                            <li>
                                <p>The username parameter defaults to username instead of j_username</p>
                            </li>
                            <li>
                                <p>The password parameter defaults to password instead of j_password</p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jc-form"><a class="anchor" href="#jc-form"></a>3.3. Java 配置和登录表单</h3>
                    <div class="paragraph">
                        <p>因为我们没有提及任何有关HTML或者JSP，你也许想要知道登录页面是从哪里来的，当你被提示去登录的时候。
                            由于Spring Security的默认配置没有明确的设置登录页面的URL，Spring Security自动生成了一个URL,
                            基于这样的插件，它被启用，并使用标准处理提交登录的URL的值，这个默认URL目标将会被用户登录后发送出去，以及类似功能。
                            </p>
                    </div>
                    <div class="paragraph">
                        <p>当大部分应用想要提供自己的登录页的时候，自动生成登陆页方便了快速地启动和运行。为了如此，我可以像下面这样更新我们的配置：</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login") <i class="conum" data-value="1"></i><b>(1)</b>
            .permitAll();        <i class="conum" data-value="2"></i><b>(2)</b>
}</code></pre>
                        </div>
                    </div>
                    <div class="colist arabic">
                        <table>
                            <tr>
                                <td><i class="conum" data-value="1"></i><b>1</b></td>
                                <td>修改后的配置指定了登录页的地址。</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="2"></i><b>2</b></td>
                                <td>我们必须授权所有用户（包含未被认证的用户）访问我们的登录页。
                                    <code>formLogin().permitAll()</code>方法允许我们授予所有用户访问与表单登录相关的所有URL的权限。</td>
                            </tr>
                        </table>
                    </div>
                    <div class="paragraph">
                        <p>对应我们当前配置，用jsp实现的样例登录页面，看起来像下面这样：</p>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    下面登录页呈现了我们的当前配置。我们能够更加容易的更新我们的配置，假如有些默认配置我们不需要我们可以不用加入。
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint html language-html"><code>&lt;c:url value="/login" var="loginUrl"/&gt;
&lt;form action="${loginUrl}" method="post"&gt;       <i class="conum" data-value="1"></i><b>(1)</b>
    &lt;c:if test="${param.error != null}"&gt;        <i class="conum" data-value="2"></i><b>(2)</b>
        &lt;p&gt;
            Invalid username and password.
        &lt;/p&gt;
    &lt;/c:if&gt;
    &lt;c:if test="${param.logout != null}"&gt;       <i class="conum" data-value="3"></i><b>(3)</b>
        &lt;p&gt;
            You have been logged out.
        &lt;/p&gt;
    &lt;/c:if&gt;
    &lt;p&gt;
        &lt;label for="username"&gt;Username&lt;/label&gt;
        &lt;input type="text" id="username" name="username"/&gt;	<i class="conum" data-value="4"></i><b>(4)</b>
    &lt;/p&gt;
    &lt;p&gt;
        &lt;label for="password"&gt;Password&lt;/label&gt;
        &lt;input type="password" id="password" name="password"/&gt;	<i class="conum" data-value="5"></i><b>(5)</b>
    &lt;/p&gt;
    &lt;input type="hidden"                        <i class="conum" data-value="6"></i><b>(6)</b>
        name="${_csrf.parameterName}"
        value="${_csrf.token}"/&gt;
    &lt;button type="submit" class="btn"&gt;Log in&lt;/button&gt;
&lt;/form&gt;</code></pre>
                        </div>
                    </div>
                    <div class="colist arabic">
                        <table>
                            <tr>
                                <td><i class="conum" data-value="1"></i><b>1</b></td>
                                <td>POST提交到<code>/login</code>路径下将会提示要认证用户信息</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="2"></i><b>2</b></td>
                                <td>如果查询参数<code>error</code>存在，提示认证失败了</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="3"></i><b>3</b></td>
                                <td>如果查询参数<code>logout</code>存在，用户成功的退出系统了</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="4"></i><b>4</b></td>
                                <td>用户必须传入且命名为<em>username</em>的HTTP请求参数</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="5"></i><b>5</b></td>
                                <td>密码必须传入且命名为<em>password</em>的HTTP请求参数</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="6"></i><b>6</b></td>
                                <td>我们必须要<a href="#csrf-include-csrf-token">包含 CSRF Token</a>的话，
                                    要了解更多，去阅读手册的<a href="#csrf">Cross Site Request Forgery (CSRF)</a>章节</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="authorize-requests"><a class="anchor" href="#authorize-requests"></a>3.4. 授权请求</h3>
                    <div class="paragraph">
                        <p>我们的应用例子中，只有必须被认证了的用户以及这样做了的每一个URL。
                            我们可以为我们的URL指定自定义的需求，通过添加多个子项到我们的<code>http.authorizeRequests()</code>方法中。举个例子：</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()                                                                <i class="conum" data-value="1"></i><b>(1)</b>
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                  <i class="conum" data-value="2"></i><b>(2)</b>
            .antMatchers("/admin/**").hasRole("ADMIN")                                      <i class="conum" data-value="3"></i><b>(3)</b>
            .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')")  <i class="conum" data-value="4"></i><b>(4)</b>
            .anyRequest().authenticated()                                                   <i class="conum" data-value="5"></i><b>(5)</b>
            .and()
        // ...
        .formLogin();
}</code></pre>
                        </div>
                    </div>
                    <div class="colist arabic">
                        <table>
                            <tr>
                                <td><i class="conum" data-value="1"></i><b>1</b></td>
                                <td>这儿有多个对应<code>http.authorizeRequests()</code>方法的子项，每一个匹配器被认为是按照顺序被申明的。</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="2"></i><b>2</b></td>
                                <td>我们指定了多个URL模式，这样任何用户都可以访问。特别地，任何用户访问一个请求，加入这个URL以"/resources/"开头，等于"/signup"，或者等于"/about"。</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="3"></i><b>3</b></td>
                                <td>任何URL以"/admin/"开头的，就会限制用户必须有"ROLE_ADMIN"角色。你会注意到自从我们调用了<code>hasRole</code>方法，我们不需要指定"ROLE_"前缀。</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="4"></i><b>4</b></td>
                                <td>任何以"/db/"开头的URL要求用户既要有"ROLE_ADMIN" 又要有"ROLE_DBA"。</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="5"></i><b>5</b></td>
                                <td>Any URL that has not already been matched on only requires that the user be authenticated</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jc-authentication"><a class="anchor" href="#jc-authentication"></a>3.5. 认证</h3>
                    <div class="paragraph">
                        <p>到此为止我们仅仅看了看最基本的认证配置。接下来让我们看看稍微高级点的可选的认证配置。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="jc-authentication-inmememory"><a class="anchor" href="#jc-authentication-inmememory"></a>3.5.1. 内存中的认证</h4>
                        <div class="paragraph">
                            <p>We have already seen an example of configuring in memory authentication for a single user. Below is an example to configure multiple users:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="jc-authentication-jdbc"><a class="anchor" href="#jc-authentication-jdbc"></a>3.5.2. JDBC的认证</h4>
                        <div class="paragraph">
                            <p>You can find the updates to suppport JDBC based authentication. The example below assumes that you have already defined a <code>DataSource</code> within your application. The <a href="https://github.com/spring-projects/spring-security/tree/master/samples/jdbc-jc">jdbc-jc sample</a> provides a complete example of using JDBC based authentication.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)
            .withDefaultSchema()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-authentication"><a class="anchor" href="#ldap-authentication"></a>3.5.3. LDAP 认证</h4>
                        <div class="paragraph">
                            <p>You can find the updates to suppport LDAP based authentication. The <a href="https://github.com/spring-projects/spring-security/tree/master/samples/ldap-jc">ldap-jc sample</a> provides a complete example of using LDAP based authentication.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups");
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The example above uses the following LDIF and an embedded Apache DS LDAP instance.</p>
                        </div>
                        <div class="listingblock">
                            <div class="title">users.ldif</div>
                            <div class="content">
                                <pre>dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people

dn: uid=admin,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Rod Johnson
sn: Johnson
uid: admin
userPassword: password

dn: uid=user,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dianne Emu
sn: Emu
uid: user
userPassword: password

dn: cn=user,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: user
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
uniqueMember: uid=user,ou=people,dc=springframework,dc=org

dn: cn=admin,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: admin
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org</pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="multiple-httpsecurity"><a class="anchor" href="#multiple-httpsecurity"></a>3.6. 多个HttpSecurity</h3>
                    <div class="paragraph">
                        <p>我们可以配置多个HttpSecurity实例，只需要我们有多个<code>&lt;http&gt;</code>代码块。 The key is to extend the <code>WebSecurityConfigurationAdapter</code> multiple times. For example, the following is an example of having a different configuration for URL`s that start with <code>/api/</code>.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) { <i class="conum" data-value="1"></i><b>(1)</b>
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }

    @Configuration
    @Order(1)                                                        <i class="conum" data-value="2"></i><b>(2)</b>
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")                               <i class="conum" data-value="3"></i><b>(3)</b>
                .authorizeRequests()
                    .anyRequest().hasRole("ADMIN")
                    .and()
                .httpBasic();
        }
    }

    @Configuration                                                   <i class="conum" data-value="4"></i><b>(4)</b>
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
    }
}</code></pre>
                        </div>
                    </div>
                    <div class="colist arabic">
                        <table>
                            <tr>
                                <td><i class="conum" data-value="1"></i><b>1</b></td>
                                <td>Configure Authentication as normal</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="2"></i><b>2</b></td>
                                <td>Create an instance of <code>WebSecurityConfigurerAdapter</code> that contains <code>@Order</code> to specify which <code>WebSecurityConfigurerAdapter</code> should be considered first.</td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="3"></i><b>3</b></td>
                                <td>The <code>http.antMatcher</code> states that this <code>HttpSecurity</code> will only be applicable to URLs that start with <code>/api/</code></td>
                            </tr>
                            <tr>
                                <td><i class="conum" data-value="4"></i><b>4</b></td>
                                <td>Create another instance of <code>WebSecurityConfigurerAdapter</code>. If the URL does not start with <code>/api/</code> this configuration will be used. This configuration is considered after <code>ApiWebSecurityConfigurationAdapter</code> since it has an <code>@Order</code> value after <code>1</code> (no <code>@Order</code> defaults to last).</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jc-method"><a class="anchor" href="#jc-method"></a>3.7. Method Security</h3>
                    <div class="paragraph">
                        <p>From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework’s original @Secured annotation. From 3.0 you can also make use of new <a href="#el-access">expression-based annotations</a>. You can apply security to a single bean, using the intercept-methods element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="enableglobalmethodsecurity"><a class="anchor" href="#enableglobalmethodsecurity"></a>3.7.1. EnableGlobalMethodSecurity</h4>
                        <div class="paragraph">
                            <p>We can enable annotation-based security using the <code>@EnableGlobalMethodSecurity</code> annotation on any <code>@Configuration</code> instance. For example, the following would enable Spring Security`s <code>@Secured</code> annotation.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
   // ...
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Security’s native annotation support defines a set of attributes for the method. These will be passed to the AccessDecisionManager for it to make the actual decision:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface BankService {

  @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  public Account readAccount(Long id);

  @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  public Account[] findAccounts();

  @Secured("ROLE_TELLER")
  public Account post(Account account, double amount);
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Support for JSR-250 annotations can be enabled using</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {
   // ...
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security’s native annotations. To use the new expression-based syntax, you would use</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
   // ...
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>and the equivalent Java code would be</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface BankService {

  @PreAuthorize("isAnonymous()")
  public Account readAccount(Long id);

  @PreAuthorize("isAnonymous()")
  public Account[] findAccounts();

  @PreAuthorize("hasAuthority('ROLE_TELLER')")
  public Account post(Account account, double amount);
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="globalmethodsecurityconfiguration"><a class="anchor" href="#globalmethodsecurityconfiguration"></a>3.7.2. GlobalMethodSecurityConfiguration</h4>
                        <div class="paragraph">
                            <p>Sometimes you may need to perform operations that are more complicated than are possible with the <code>@EnableGlobalMethodSecurity</code> annotation allow. For these instances, you can extend the <code>GlobalMethodSecurityConfiguration</code> ensuring that the <code>@EnableGlobalMethodSecurity</code> annotation is present on your subclass. For example, if you wanted to provide a custom <code>MethodSecurityExpressionHander</code>, you could use the following configuration:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        // ... create and return custom MethodSecurityExpressionHandler ...
        return expressionHander;
    }
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>For additional information about methods that can be overriden, refer to the <code>GlobalMethodSecurityConfiguration</code> Javadoc.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="post-processing-configured-objects"><a class="anchor" href="#post-processing-configured-objects"></a>3.8. Post Processing Configured Objects</h3>
                    <div class="paragraph">
                        <p>Spring Security`s Java Configuration does not expose every property of every object that it configures. This simplifies the configuration for a majority of users. Afterall, if every property was exposed, users could use standard bean configuration.</p>
                    </div>
                    <div class="paragraph">
                        <p>While there are good reasons to not directly expose every property, users may still need more advanced configuration options. To address this Spring Security introduces the concept of an <code>ObjectPostProcessor</code> which can used to modify or replace many of the Object instances created by the Java Configuration. For example, if you wanted to configure the <code>filterSecurityPublishAuthorizationSuccess</code> property on <code>FilterSecurityInterceptor</code> you could use the following:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .withObjectPostProcessor(new ObjectPostProcessor&lt;FilterSecurityInterceptor&gt;() {
                public &lt;O extends FilterSecurityInterceptor&gt; O postProcess(
                        O fsi) {
                    fsi.setPublishAuthorizationSuccess(true);
                    return fsi;
                }
            });
}</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="ns-config"><a class="anchor" href="#ns-config"></a>4. Security 命名空间配置</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="introduction-2"><a class="anchor" href="#introduction-2"></a>4.1. 介绍</h3>
                    <div class="paragraph">
                        <p>命名空间配置从Spring framework 2.0就可以用了。通过添加xml架构，来给你补充传统的Spring beans上下文元素的语法。
                            你可以在Spring<a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html">线上手册文档</a>中找到更多信息。
                            命 名空间元素可以简单的配置单个bean， 或使用更强大的， 定义一个备用配置语法， 这可以更加紧密的匹配问题域，隐藏用户背后的复杂性。
                            简单元素可能隐藏事实，多种bean和 处理步骤添加到应用环境中。
                            比如， 把下面的security命名元素添加到应用环境中， 将会为测试用途，在应用内部启动一个内嵌LDAP服务器：</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;security:ldap-server /&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>这比配置一个Apache目录服务bean要简单的多。最常见的替代配置需求都可以使用<code>ldap-server</code>元素的属性进行配置，这样用户就不用担心他们需要设置什么，不用担心bean里的各种属性<span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>。 使用一个良好的XML编辑器来编辑应用环境文件， 应该提供可用的属性和元素信息。我们推荐你尝试一下<a href="http://www.springsource.com/products/sts">SpringSource Tool Suite</a> 为它具有处理spring组合命名空间的特殊功能。</p>
                    </div>
                    <div class="paragraph">
                        <p>将security命名空间使用到你的应用环境中之前，你需要将<code>spring-security-config</code>jar添加到你的classpath下。然后 你需要将模式声明添加到你的application context文件中:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security.xsd"&gt;
    ...
&lt;/beans&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>在很多例子里，你将会看到（包括示例中）的应用，我们经常用"security"作为默认命名空间而不是"beans",
                            这就意味着我们可以在所有security命名空间元素中忽略前缀，使得内容更易读。
                            你也许想要这样，如果你的应用程序上下文分割成单独文件而且大部分security配置都在同一个文件中。
                            你的security应用程序上下文文件将要像这样开头：</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security.xsd"&gt;
    ...
&lt;/beans:beans&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>在本章中，我们将会采用这种语法。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="design-of-the-namespace"><a class="anchor" href="#design-of-the-namespace"></a>4.1.1. 命名空间的设计</h4>
                        <div class="paragraph">
                            <p>名空间被用来设计成， 处理框架内最常见的功能， 提供一个简化和简洁的语法， 使他们在一个应用程序里。
                                这种设计是基于框架内的大型依赖，可以分割成下面这些部分：</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><em>Web/HTTP Security</em> - 最复杂的部分。设置过滤器和相关的服务 bean来应用框架验证机制，保护 URL，渲染登录和错误页面还有更多。</p>
                                </li>
                                <li>
                                    <p><em>Business Object (Method) Security</em> - 保护服务层安全（可选）</p>
                                </li>
                                <li>
                                    <p><em>AuthenticationManager</em> - 处理来自其它系统框架请求的认证</p>
                                </li>
                                <li>
                                    <p><em>AccessDecisionManager</em> - 供访问的决定， 适用于Web Security和Method Security。 A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.</p>
                                </li>
                                <li>
                                    <p><em>AuthenticationProviders</em> - 验证管理器验证用户的机制。 该命名空间提供几种标准选项，意味着使用传统语法添加自定义bean。</p>
                                </li>
                                <li>
                                    <p><em>UserDetailsService</em> - 和认证提供器紧密联系的，但是常常也是被其它bean所需要的。</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>We`ll see how to configure these in the following sections.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ns-getting-started"><a class="anchor" href="#ns-getting-started"></a>4.2. Security命名空间配置</h3>
                    <div class="paragraph">
                        <p>在本节中，我们来看看如何使用一些框架里的主要配置，建立一个命名空间配置。
                            我们假 设你最初想要尽快的启动运行，为已有的 web应用添加认证支持和权限控制，使用一些测 试登录。
                            然后我们看一下如何修改一下， 使用数据库或其他安全信息参数。
                            在以后的章节 里我们将引入更多高级的命名空间配置选项。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-web-xml"><a class="anchor" href="#ns-web-xml"></a>4.2.1. web.xml 配置</h4>
                        <div class="paragraph">
                            <p>你需要做的第一件事是添加下面的过滤器声明到你的<code>web.xml</code> 文件中:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;filter&gt;
  &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
  &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
  &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This provides a hook into the Spring Security web infrastructure. <code>DelegatingFilterProxy</code> is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you`ve added this to your <code>web.xml</code>, you`re ready to start editing your application context file. Web security services are configured using the <code>&lt;http&gt;</code> element.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-minimal"><a class="anchor" href="#ns-minimal"></a>4.2.2. 一个最小化的&lt;http&gt;配置</h4>
                        <div class="paragraph">
                            <p>你只需要以下面这样开头，就可以启用web security：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt;
  &lt;form-login /&gt;
  &lt;logout /&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>这就是说，在我们的应用程序中，我们想要被保护的全部URL，只有拥有<code>ROLE_USER</code>角色的用户才能访问,
                                我们想要登录到应用程序中，需要通过带有用户名和密码的表单才行，还有，我们想要退出系统，需要通过被注册为允许我们退出应用的URL。
                                我们想要一个使用用户名和密码来登录应用程序的表单，而且我们想要一个被注册为允许我们退出系统的URL。
                                <code>&lt;http&gt;</code>元素是所有web相关功能的命名空间的父级元素。
                                <code>&lt;intercept-url&gt;</code>元素定义了一个<code>pattern</code>，它是被用来匹配即将请求的URL，并使用ant样式路径的语法<span class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnote_2" title="View footnote.">2</a>]</span>匹配。
                                你也可以使用正则表达式匹配，来作为备选方案。（详见 附录.命名空间部分获取更详细信息）。
                                <code>access</code>属性定义了，用来在指定模式下匹配，请求的访问条件。
                                使用默认的配置， 这个是一个典型的以逗号分隔的角色队列，任何一个必须被允许访问请求。
                                前缀"ROLE_"标注，它显示出 用户应该授予的权限的一个简单对比。
                                换句话说，一个正常基于角色的检查正被使用。
                                在 Spring Security中的访问控制不去限制简单角色的用户（因此使用前缀来区分不同的安全类型）。
                                我们后面将会解释如何变化<span class="footnote">[<a id="_footnoteref_3" class="footnote" href="#_footnote_3" title="View footnote.">3</a>]</span>。</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>你可以使用多个<code>&lt;intercept-url&gt;</code>元素，为不同URL的集合 定义不同的访问需求， 它们会被归入一个有序队列中，每次取出最先匹配的一个元素使用。
                                                所以你必须把最符合匹配条件的放到最上边。
                                                你也可以添加一个<code>method</code>属性，来限制符合一个特定HTTP方法（<code>GET</code>, <code>POST</code>, <code>PUT</code>等等）的匹配规则。</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>要是想添加一些用户，你可以直接使用下面的命名空间直接定义一些测试数据：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;authentication-manager&gt;
  &lt;authentication-provider&gt;
    &lt;user-service&gt;
      &lt;user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" /&gt;
      &lt;user name="bob" password="bobspassword" authorities="ROLE_USER" /&gt;
    &lt;/user-service&gt;
  &lt;/authentication-provider&gt;
&lt;/authentication-manager&gt;</code></pre>
                            </div>
                        </div>
                        <div class="sidebarblock">
                            <div class="content">
                                <div class="paragraph">
                                    <p>如果你熟悉之前版本的框架中的命名空间，你可能已经猜到这里发生了什么。
                                        <code>&lt;http&gt;</code>元素负责创建一个<code>FilterChainProxy</code>和他要用到的filter bean。
                                        像不正确顺序Filter的常见问题，不再会出现了，因为Filter的位置已经被预先定义了。</p>
                                </div>
                                <div class="paragraph">
                                    <p><code>&lt;authentication-provider&gt;</code>元素创建了一个<code>DaoAuthenticationProvider</code>bean同时<code>&lt;user-service&gt;</code>元素创建了一个<code>InMemoryDaoImpl</code>。
                                        所有的<code>authentication-provider</code>元素必须是<code>&lt;authentication-manager&gt;</code>元素的子元素，它创建了一个<code>ProviderManager</code>元素，同时通过ProviderManager注册了authentication providers。
                                        在<a href="#appendix-namespace">命名空间附录</a>中，你可以找到更多关于bean被创建的详细信息。
                                        如果你想要开始理解框架中重要的类，还有它们是如何工作的，特别是你想要在以后去自定义某些东西，反复阅读这里是值得的。</p>
                                </div>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>上面的配置定义了两个用户，他们的密码和角色都包含在应用程序中（这将用于访问控制）。
                                从一个标准的配置文件中加载用户信息也是可以的，只需要在<code>user-service</code>中设置<code>properties</code>属性。
                                查看<a href="#core-services-in-memory-service">in-memory authentication</a>章节获取更多文件格式的详细信息。
                                使用<code>&lt;authentication-provider&gt;</code>元素意味着用户的信息将会被认证管理器所使用，用来处理认证请求。
                                你可以用多个<code>&lt;authentication-provider&gt;</code>元素去定义不同的认证来源，同时它们会被依次询问（是否认证通过）。</p>
                        </div>
                        <div class="paragraph">
                            <p>在此时，你应该可以启动你的应用程序，同时你会被要求登录以继续。
                                尝试一下，或者尝试实验一下，框架中自带的tutorial例子应用程序。</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-form-and-basic"><a class="anchor" href="#ns-form-and-basic"></a>4.2.3. 表单和基本登录选项</h4>
                        <div class="paragraph">
                            <p>当你被提示要求登录的时候，你也许会疑惑于登录表单从哪里，由于我们到现在都没有提及任何HTML文件或者JSP文件。
                                事实上，由于我们没有明确地为登录页设置一个URL路径，Spring Security基于插件自动生成了一个，
                                它被启用，并使用标准处理提交登录的URL的值，这个默认URL目标将会被用户登录后发送出去，以及等等功能。
                                然而，命名空间提供了大量的支持来让你自定义这些属性。
                                举个例子，如果你想要使用你自己的登录页面，你可以这样使用：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt;
  &lt;form-login login-page='/login.jsp'/&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>还有要注意的是，我们添加了一个额外的<code>intercept-url</code>元素来说明登录请求对于匿名用户是可用的<span class="footnote">[<a id="_footnoteref_4" class="footnote" href="#_footnote_4" title="View footnote.">4</a>]</span>，
                                还说明<a href="#authz-authenticated-voter">AuthenticatedVoter</a>类如何处理值为<code>IS_AUTHENTICATED_ANONYMOUSLY</code>的详细信息。
                                否则，请求会被模式<code>/**</code>所匹配，同时，登录页自己都不能访问到自己了!
                                这是一个很常见的配置错误，它会导致系统出现无限循环。
                                如果你的登录页面是被保护的，Spring Security会在日志中发出一个警告。

                                可能让所有的请求都匹配特定的模式，通过完全的安全过滤器链，为这样的模式定义一个单独的<code>http</code>元素，如下：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http pattern="/css/**" security="none"/&gt;
&lt;http pattern="/login.jsp*" security="none"/&gt;

&lt;http&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt;
  &lt;form-login login-page='/login.jsp'/&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>从Spring Security 3.1开始到现在，可以使用多个<code>http</code>元素定义分开的security过滤器链，这样可以为不同的请求模式配置。
                                如果在<code>http</code>元素中<code>pattern</code>属性被遗漏，它将匹配所有请求。
                                要创建一个不安全的匹配模式，这样的语法是一个简单的例子。这样的模式和一个空的过滤器链<span class="footnote">[<a id="_footnoteref_5" class="footnote" href="#_footnote_5" title="View footnote.">5</a>]</span>关联。
                                在<a href="#filter-chains-with-ns">Security Filter Chain</a>章节中，我们将会更详细的看到这样的新语法。</p>
                        </div>
                        <div class="paragraph">
                            <p>意识到这些不安全的请求，对于任何Spring Security和web相关的配置或者附加选项，比如<code>requires-channel</code>都会被完全的忽略，这是很重要的。
                                在请求不安全的请求时，你将不能访问当前用户信息或者调用保护了的方法。
                                如果你依然要使用security 过滤器链，那么请使用<code>access='IS_AUTHENTICATED_ANONYMOUSLY'</code>作为一种替代选择。</p>
                        </div>
                        <div class="paragraph">
                            <p>如果你想要使用基本认证来替换表单登录，那么像这样改变配置</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt;
  &lt;http-basic /&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>基本身份认证会优先被调用，同时，当用户访问一个受保护的资源时，也会用来提示用户登录。
                                如果你希望使用表单登录，在配置中它依然是可用的，比如，把一个登录表单内嵌到其他页面里。</p>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-form-target"><a class="anchor" href="#ns-form-target"></a>设置一个默认的提交登录目标</h5>
                            <div class="paragraph">
                                <p>假如要去访问一个受保护的资源时，登录表单没有任何提示，那么<code>default-target-url</code>选项该登场了。
                                    它是用户成功登录后的URL,默认到"/"。
                                    你同样可以配置，通过设置<code>always-use-default-target</code>属性为"true"，这样用户<em>总是</em>最终到这个页面
                                    （不管登录是“跳转过来的”，还是明确的选择登录）。
                                    如果你的系统一直需要用户从首页进入，这样就是很有用的，比如：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;http pattern="/login.htm*" security="none"/&gt;
&lt;http&gt;
  &lt;intercept-url pattern='/**' access='ROLE_USER' /&gt;
  &lt;form-login login-page='/login.htm' default-target-url='/home.htm'
          always-use-default-target='true' /&gt;
&lt;/http&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>要进行更多的登录目标控制，你可以使用<code>authentication-success-handler-ref</code>属性，作为<code>default-target-url</code>的替代选择。
                                    它所引用的bean必须是<code>AuthenticationSuccessHandler</code>的一个实例。
                                    在<a href="#form-login-flow-handling">Core Filters</a>章节，还有在附录命名空间部分中，你会找到更多关于这些的信息，也有关于如何自定义认证失败时的流程的信息。
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-logout"><a class="anchor" href="#ns-logout"></a>4.2.4. 退出处理</h4>
                        <div class="paragraph">
                            <p><code>logout</code>元素的增加，是为了支持退出系统到指定的URL的。
                                默认退出URL地址是<code>/j_spring_security_logout</code>，但是可以设置一个别的什么，通过使用<code>logout-url</code>属性。
                                更多其它可用属性的信息，你可以在附录命名空间部分找到。</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-auth-providers"><a class="anchor" href="#ns-auth-providers"></a>4.2.5. 使用其它认证提供器</h4>
                        <div class="paragraph">
                            <p>在实践中，你将会需要更多可拓展的用户信息来源比几个添加到应用程序上下文文件中。
                                Most likely you will want to store your user information in something like a database or an LDAP server.
                                LDAP namespace configuration is dealt with in the <a href="#ldap">LDAP chapter</a>, so we won`t cover it here.
                                If you have a custom implementation of Spring Security`s <code>UserDetailsService</code>, called "myUserDetailsService" in your application context,
                                then you can authenticate against this using</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
  &lt;authentication-manager&gt;
    &lt;authentication-provider user-service-ref='myUserDetailsService'/&gt;
  &lt;/authentication-manager&gt;
</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>如果你想要使用数据库，那么你可以使用</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;authentication-manager&gt;
  &lt;authentication-provider&gt;
    &lt;jdbc-user-service data-source-ref="securityDataSource"/&gt;
  &lt;/authentication-provider&gt;
&lt;/authentication-manager&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>在"securityDataSource"的那里是<code>DataSource</code>bean在应用程序上下文中的名称，
                                指向一个包含着标准Spring Security<a href="#db_schema_users_authorities">用户数据的表</a>的数据库。
                                作为备选项，你可以配置一个Spring Security <code>JdbcDaoImpl</code>的bean，并且使用<code>user-service-ref</code>属性来指向它：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;authentication-manager&gt;
  &lt;authentication-provider user-service-ref='myUserDetailsService'/&gt;
&lt;/authentication-manager&gt;

&lt;beans:bean id="myUserDetailsService"
    class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"&gt;
  &lt;beans:property name="dataSource" ref="dataSource"/&gt;
&lt;/beans:bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>你也可以使用标准的<code>AuthenticationProvider</code>bean，如下：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
  &lt;authentication-manager&gt;
    &lt;authentication-provider ref='myAuthenticationProvider'/&gt;
  &lt;/authentication-manager&gt;
</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>
                                where <code>myAuthenticationProvider</code> is the name of a bean in your application context which implements <code>AuthenticationProvider</code>.
                                You can use multiple <code>authentication-provider</code> elements, in which case the providers will be queried in the order they are declared. See <a href="#ns-auth-manager">The Authentication Manager and the Namespace</a> for more on information on how the Spring Security <code>AuthenticationManager</code> is configured using the namespace.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-password-encoder"><a class="anchor" href="#ns-password-encoder"></a>添加一个密码编码器</h5>
                            <div class="paragraph">
                                <p>密码应该总是使用安全散列算法编码（而非一个标准的算法，比如SHA或者MD5）。
                                    这是通过<code>&lt;password-encoder&gt;</code>元素来支持的。
                                    通过bcrypt来编码密码，原始的认证提供器配置方式将会想下面这样：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;beans:bean name="bcryptEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/&gt;

&lt;authentication-manager&gt;
  &lt;authentication-provider&gt;
    &lt;password-encoder ref="bcryptEncoder"/&gt;
    &lt;user-service&gt;
      &lt;user name="jimi" password="d7e6351eaa13189a5a3641bab846c8e8c69ba39f"
            authorities="ROLE_USER, ROLE_ADMIN" /&gt;
      &lt;user name="bob" password="4e7421b1b8765d8f9406d87e7cc6aa784c4ab97f"
            authorities="ROLE_USER" /&gt;
    &lt;/user-service&gt;
  &lt;/authentication-provider&gt;
&lt;/authentication-manager&gt;
</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>Bcrypt在大多数选项中是一个不错的选择，除非你的遗留系统是使用的不同的算法。
                                    如果你正在使用一个简单哈希算法，或者更糟糕的，存储的是明文密码，
                                    那么你应该考虑迁移到一个更加安全的备选项，比如bcrypt。</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ns-web-advanced"><a class="anchor" href="#ns-web-advanced"></a>4.3. 高级 Web 插件</h3>
                    <div class="sect3">
                        <h4 id="ns-remember-me"><a class="anchor" href="#ns-remember-me"></a>4.3.1. Remember-Me 认证</h4>
                        <div class="paragraph">
                            <p>See the separate <a href="#remember-me">Remember-Me chapter</a> for information on remember-me namespace configuration.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-requires-channel"><a class="anchor" href="#ns-requires-channel"></a>4.3.2. 添加 HTTP/HTTPS 通道 Security</h4>
                        <div class="paragraph">
                            <p>If your application supports both HTTP and HTTPS, and you require that particular URLs can only be accessed over HTTPS, then this is directly supported using the <code>requires-channel</code> attribute on <code>&lt;intercept-url&gt;</code>:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;intercept-url pattern="/secure/**" access="ROLE_USER" requires-channel="https"/&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" requires-channel="any"/&gt;
  ...
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>With this configuration in place, if a user attempts to access anything matching the "/secure/**" pattern using HTTP, they will first be redirected to an HTTPS URL <span class="footnote">[<a id="_footnoteref_6" class="footnote" href="#_footnote_6" title="View footnote.">6</a>]</span>. The available options are "http", "https" or "any". Using the value "any" means that either HTTP or HTTPS can be used.</p>
                        </div>
                        <div class="paragraph">
                            <p>If your application uses non-standard ports for HTTP and/or HTTPS, you can specify a list of port mappings as follows:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;port-mappings&gt;
    &lt;port-mapping http="9080" https="9443"/&gt;
  &lt;/port-mappings&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Note that in order to be truly secure, an application should not use HTTP at all or switch between HTTP and HTTPS. It should start in HTTPS (with the user entering an HTTPS URL) and use a secure connection throughout to avoid any possibility of man-in-the-middle attacks.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-session-mgmt"><a class="anchor" href="#ns-session-mgmt"></a>4.3.3. Session 管理</h4>
                        <div class="sect4">
                            <h5 id="detecting-timeouts"><a class="anchor" href="#detecting-timeouts"></a>删除超时Session</h5>
                            <div class="paragraph">
                                <p>你可以配置Spring Security来监测提交一个无效session ID ，并且将用户重定向到恰当的URL。
                                    这是通过<code>session-management</code>元素来实现的：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;session-management invalid-session-url="/invalidSession.htm" /&gt;
&lt;/http&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>注意，如果你使用这个机制来监测session超时，
                                    当用户注销后在没有关闭浏览器的时候又重新登录时，它有可能错误的报告一个错误。
                                    这是因为，当你让session失效，以及即使用户已经注销又重复提交时，session cookie没有被清空。
                                    你也许在注销时可以明确地删除JSESSIONID cookie，例如，在注销处理中使用下面语法：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;logout delete-cookies="JSESSIONID" /&gt;
&lt;/http&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>不幸的是，这种方式并不能保证在所有servlet容器中都能正常运行，所以你需要在你自己的环境下测试。 </p>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            <div class="paragraph">
                                                <p>如果你的应用程序运行在一个代理的后面，你也许可以通过配置代理服务器来移除session cookie。
                                                    If you are running your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server.
                                                    例如，使用Apache HTTPD的mod_headers，下面指令将会删除<code>JSESSIONID</code>cookie，
                                                    通过在一个注销请求的响应中使其超期的方式（假设应用程序部署在路径<code>/tutorial</code>下）：</p>
                                            </div>
                                            <div class="listingblock">
                                                <div class="content">
                                                    <pre class="prettyprint xml language-xml"><code>&lt;LocationMatch "/tutorial/j_spring_security_logout"&gt;
  Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"
&lt;/LocationMatch&gt;</code></pre>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-concurrent-sessions"><a class="anchor" href="#ns-concurrent-sessions"></a>并发 Session 控制</h5>
                            <div class="paragraph">
                                <p>如果你想限制单个用户登录到您的应用程序，Spring Security通过下面简单添加项来方便的支持使用。
                                    首先你需要添加下面监听器到你的<code>web.xml</code>文件中，这样让Spring Security持续的对session生命周期事件的监听：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;listener&gt;
  &lt;listener-class&gt;
    org.springframework.security.web.session.HttpSessionEventPublisher
  &lt;/listener-class&gt;
&lt;/listener&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>然后添加下面几行到你的应用程序上下文中：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;session-management&gt;
     &lt;concurrency-control max-sessions="1" /&gt;
  &lt;/session-management&gt;
&lt;/http&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>这个将阻止用登录多次——第二次登录将会导致第一次的session失效。
                                    通常你会更愿意阻止第二次登录，在这样的情况下你可以使用：</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;session-management&gt;
     &lt;concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /&gt;
  &lt;/session-management&gt;
&lt;/http&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>第二次登录就会被拒绝。通过“拒绝”，我们的意思是，假如用户是基于表单登录的，用户将会送到<code>authentication-failure-url</code>。
                                    如果第二次认证发生在另一种非交互的机制，比如，“记住我”，
                                    一个“未被认证”的错误将会发送到客户端。
                                    如果你想要使用一个错误提示页面，你可以增加一个<code>session-authentication-error-url</code>属性到<code>session-management</code>元素中。
                            </div>
                            <div class="paragraph">
                                <p>如果你在为登录表单使用一个自定义的认证过滤器，那么你不得不明确地配置并发session控制。
                                    更多详情请到<a href="#session-mgmt">Session 管理章节</a>中查看。</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-session-fixation"><a class="anchor" href="#ns-session-fixation"></a>Session Fixation Attack Protection</h5>
                            <div class="paragraph">
                                <p><a href="http://en.wikipedia.org/wiki/Session_fixation">Session fixation</a> attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example). Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in. If you don`t require this protection, or it conflicts with some other requirement, you can control the behavior using the <code>session-fixation-protection</code> attribute on <code>&lt;session-management&gt;</code>, which has four options</p>
                            </div>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><code>none</code> - Don`t do anything. The original session will be retained.</p>
                                    </li>
                                    <li>
                                        <p><code>newSession</code> - Create a new "clean" session, without copying the existing session data (Spring Security-related attributes will still be copied).</p>
                                    </li>
                                    <li>
                                        <p><code>migrateSession</code> - Create a new session and copy all existing session attributes to the new session. This is the default in Servlet 3.0 or older containers.</p>
                                    </li>
                                    <li>
                                        <p><code>changeSessionId</code> - Do not create a new session. Instead, use the session fixation protection provided by the Servlet container (<code>HttpServletRequest#changeSessionId()</code>). This option is only available in Servlet 3.1 (Java EE 7) and newer containers. Specifying it in older containers will result in an exception. This is the default in Servlet 3.1 and newer containers.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="paragraph">
                                <p>When session fixation protection occurs, it results in a <code>SessionFixationProtectionEvent</code> being published in the application context. If you use <code>changeSessionId</code>, this protection will <em>also</em> result in any <code>javax.servlet.http.HttpSessionIdListener</code> s being notified, so use caution if your code listens for both events. See the <a href="#session-mgmt">Session Management</a> chapter for additional information.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-openid"><a class="anchor" href="#ns-openid"></a>4.3.4. OpenID Support</h4>
                        <div class="paragraph">
                            <p>The namespace supports <a href="http://openid.net/">OpenID</a> login either instead of, or in addition to normal form-based login, with a simple change:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  &lt;intercept-url pattern="/**" access="ROLE_USER" /&gt;
  &lt;openid-login /&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You should then register yourself with an OpenID provider (such as myopenid.com), and add the user information to your in-memory <code>&lt;user-service&gt;</code> :</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;user name="http://jimi.hendrix.myopenid.com/" authorities="ROLE_USER" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You should be able to login using the <code>myopenid.com</code> site to authenticate. It is also possible to select a specific <code>UserDetailsService</code> bean for use OpenID by setting the <code>user-service-ref</code> attribute on the <code>openid-login</code> element. See the previous section on <a href="#ns-auth-providers">authentication providers</a> for more information. Note that we have omitted the password attribute from the above user configuration, since this set of user data is only being used to load the authorities for the user. A random password will be generate internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="attribute-exchange"><a class="anchor" href="#attribute-exchange"></a>Attribute Exchange</h5>
                            <div class="paragraph">
                                <p>Support for OpenID <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html">attribute exchange</a>. As an example, the following configuration would attempt to retrieve the email and full name from the OpenID provider, for use by the application:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;openid-login&gt;
  &lt;attribute-exchange&gt;
    &lt;openid-attribute name="email" type="http://axschema.org/contact/email" required="true"/&gt;
    &lt;openid-attribute name="name" type="http://axschema.org/namePerson"/&gt;
  &lt;/attribute-exchange&gt;
&lt;/openid-login&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The "type" of each OpenID attribute is a URI, determined by a particular schema, in this case <a href="http://axschema.org/">http://axschema.org/</a>. If an attribute must be retrieved for successful authentication, the <code>required</code> attribute can be set. The exact schema and attributes supported will depend on your OpenID provider. The attribute values are returned as part of the authentication process and can be accessed afterwards using the following code:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>OpenIDAuthenticationToken token =
    (OpenIDAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
List&lt;OpenIDAttribute&gt; attributes = token.getAttributes();</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The <code>OpenIDAttribute</code> contains the attribute type and the retrieved value (or values in the case of multi-valued attributes). We`ll see more about how the <code>SecurityContextHolder</code> class is used when we look at core Spring Security components in the <a href="#core-components">technical overview</a> chapter. Multiple attribute exchange configurations are also be supported, if you wish to use multiple identity providers. You can supply multiple <code>attribute-exchange</code> elements, using an <code>identifier-matcher</code> attribute on each. This contains a regular expression which will be matched against the OpenID identifier supplied by the user. See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-headers"><a class="anchor" href="#ns-headers"></a>4.3.5. 响应头</h4>
                        <div class="paragraph">
                            <p>For additional information on how to customize the headers element refer to the <a href="#headers">Security HTTP Response Headers</a> section of the reference.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-custom-filters"><a class="anchor" href="#ns-custom-filters"></a>4.3.6. Adding in Your Own Filters</h4>
                        <div class="paragraph">
                            <p>If you`ve used Spring Security before, you`ll know that the framework maintains a chain of filters in order to apply its services. You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there isn`t currently a namespace configuration option (CAS, for example). Or you might want to use a customized version of a standard namespace filter, such as the <code>UsernamePasswordAuthenticationFilter</code> which is created by the <code>&lt;form-login&gt;</code> element, taking advantage of some of the extra configuration options which are available by using the bean explicitly. How can you do this with namespace configuration, since the filter chain is not directly exposed?</p>
                        </div>
                        <div class="paragraph">
                            <p>The order of the filters is always strictly enforced when using the namespace. When the application context is being created, the filter beans are sorted by the namespace handling code and the standard Spring Security filters each have an alias in the namespace and a well-known position.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>In previous versions, the sorting took place after the filter instances had been created, during post-processing of the application context. In version 3.0+ the sorting is now done at the bean metadata level, before the classes have been instantiated. This has implications for how you add your own filters to the stack as the entire filter list must be known during the parsing of the <code>&lt;http&gt;</code> element, so the syntax has changed slightly in 3.0.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>The filters, aliases and namespace elements/attributes which create the filters are shown in <a href="#filter-stack">Standard Filter Aliases and Ordering</a>. The filters are listed in the order in which they occur in the filter chain.</p>
                        </div>
                        <table id="filter-stack" class="tableblock frame-all grid-all" style="width:100%; ">
                            <caption class="title">Table 1. Standard Filter Aliases and Ordering</caption>
                            <colgroup>
                                <col style="width:33%;">
                                <col style="width:33%;">
                                <col style="width:33%;">
                            </colgroup>
                            <thead>
                                <tr>
                                    <th class="tableblock halign-left valign-top">Alias</th>
                                    <th class="tableblock halign-left valign-top">Filter Class</th>
                                    <th class="tableblock halign-left valign-top">Namespace Element or Attribute</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">CHANNEL_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>ChannelProcessingFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/intercept-url@requires-channel</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">SECURITY_CONTEXT_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>SecurityContextPersistenceFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">CONCURRENT_SESSION_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>ConcurrentSessionFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>session-management/concurrency-control</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">HEADERS_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>HeaderWriterFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/headers</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">CSRF_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>CsrfFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/csrf</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">LOGOUT_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>LogoutFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/logout</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">X509_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>X509AuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/x509</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">PRE_AUTH_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>AstractPreAuthenticatedProcessingFilter</code> Subclasses</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">N/A</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">CAS_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>CasAuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">N/A</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">FORM_LOGIN_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>UsernamePasswordAuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/form-login</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">BASIC_AUTH_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>BasicAuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/http-basic</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">SERVLET_API_SUPPORT_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>SecurityContextHolderAwareRequestFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/@servlet-api-provision</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">JAAS_API_SUPPORT_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>JaasApiIntegrationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/@jaas-api-provision</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">REMEMBER_ME_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>RememberMeAuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/remember-me</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">ANONYMOUS_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>AnonymousAuthenticationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http/anonymous</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">SESSION_MANAGEMENT_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>SessionManagementFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>session-management</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">EXCEPTION_TRANSLATION_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>ExceptionTranslationFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">FILTER_SECURITY_INTERCEPTOR</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>FilterSecurityInterceptor</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>http</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">SWITCH_USER_FILTER</p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>SwitchUserFilter</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">N/A</p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <div class="paragraph">
                            <p>You can add your own filter to the stack, using the <code>custom-filter</code> element and one of these names to specify the position your filter should appear at:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
   &lt;custom-filter position="FORM_LOGIN_FILTER" ref="myFilter" /&gt;
&lt;/http&gt;

&lt;beans:bean id="myFilter" class="com.mycompany.MySpecialAuthenticationFilter"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You can also use the <code>after</code> or <code>before</code> attributes if you want your filter to be inserted before or after another filter in the stack. The names "FIRST" and "LAST" can be used with the <code>position</code> attribute to indicate that you want your filter to appear before or after the entire stack, respectively.</p>
                        </div>
                        <div class="admonitionblock tip">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-tip" title="Tip"></i>
                                    </td>
                                    <td class="content">
                                        <div class="title">避免过滤器位置冲突</div>
                                        <div class="paragraph">
                                            <p>If you are inserting a custom filter which may occupy the same position as one of the standard filters created by the namespace then it`s important that you don`t include the namespace versions by mistake. Remove any elements which create filters whose functionality you want to replace.</p>
                                        </div>
                                        <div class="paragraph">
                                            <p>Note that you can`t replace filters which are created by the use of the <code>&lt;http&gt;</code> element itself - <code>SecurityContextPersistenceFilter</code>, <code>ExceptionTranslationFilter</code> or <code>FilterSecurityInterceptor</code>. Some other filters are added by default, but you can disable them. An <code>AnonymousAuthenticationFilter</code> is added by default and unless you have <a href="#ns-session-fixation">session-fixation protection</a> disabled, a <code>SessionManagementFilter</code> will also be added to the filter chain.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>If you`re replacing a namespace filter which requires an authentication entry point (i.e. where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource), you will need to add a custom entry point bean too.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-entry-point-ref"><a class="anchor" href="#ns-entry-point-ref"></a>Setting a Custom AuthenticationEntryPoint</h5>
                            <div class="paragraph">
                                <p>If you aren`t using form login, OpenID or basic authentication through the namespace, you may want to define an authentication filter and entry point using a traditional bean syntax and link them into the namespace, as we`ve just seen. The corresponding <code>AuthenticationEntryPoint</code> can be set using the <code>entry-point-ref</code> attribute on the <code>&lt;http&gt;</code> element.</p>
                            </div>
                            <div class="paragraph">
                                <p>The CAS sample application is a good example of the use of custom beans with the namespace, including this syntax. If you aren`t familiar with authentication entry points, they are discussed in the <a href="#tech-intro-auth-entry-point">technical overview</a> chapter.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ns-method-security"><a class="anchor" href="#ns-method-security"></a>4.4. Method Security</h3>
                    <div class="paragraph">
                        <p>From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework`s original <code>@Secured</code> annotation. From 3.0 you can also make use of new <a href="#el-access">expression-based annotations</a>. You can apply security to a single bean, using the <code>intercept-methods</code> element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-global-method"><a class="anchor" href="#ns-global-method"></a>4.4.1. The &lt;global-method-security&gt; Element</h4>
                        <div class="paragraph">
                            <p>This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context. You should only declare one <code>&lt;global-method-security&gt;</code> element. The following declaration would enable support for Spring Security`s <code>@Secured</code>:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;global-method-security secured-annotations="enabled" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Security`s native annotation support defines a set of attributes for the method. These will be passed to the <code>AccessDecisionManager</code> for it to make the actual decision:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface BankService {

  @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  public Account readAccount(Long id);

  @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  public Account[] findAccounts();

  @Secured("ROLE_TELLER")
  public Account post(Account account, double amount);
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Support for JSR-250 annotations can be enabled using</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;global-method-security jsr250-annotations="enabled" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security`s native annotations. To use the new expression-based syntax, you would use</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;global-method-security pre-post-annotations="enabled" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>and the equivalent Java code would be</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface BankService {

  @PreAuthorize("isAnonymous()")
  public Account readAccount(Long id);

  @PreAuthorize("isAnonymous()")
  public Account[] findAccounts();

  @PreAuthorize("hasAuthority('ROLE_TELLER')")
  public Account post(Account account, double amount);
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user`s list of authorities.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled). If you want to secure instances which are not created by Spring (using the <code>new</code> operator, for example) then you need to use AspectJ.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise. If two annotations are found which apply to a particular method, then only one of them will be applied.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="sect4">
                            <h5 id="ns-protect-pointcut"><a class="anchor" href="#ns-protect-pointcut"></a>Adding Security Pointcuts using protect-pointcut</h5>
                            <div class="paragraph">
                                <p>The use of <code>protect-pointcut</code> is particularly powerful, as it allows you to apply security to many beans with only a simple declaration. Consider the following example:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;global-method-security&gt;
  &lt;protect-pointcut expression="execution(* com.mycompany.*Service.*(..))"
       access="ROLE_USER"/&gt;
&lt;/global-method-security&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>This will protect all methods on beans declared in the application context whose classes are in the <code>com.mycompany</code> package and whose class names end in "Service". Only users with the <code>ROLE_USER</code> role will be able to invoke these methods. As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used. Security annotations take precedence over pointcuts.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ns-access-manager"><a class="anchor" href="#ns-access-manager"></a>4.5. The Default AccessDecisionManager</h3>
                    <div class="paragraph">
                        <p>This section assumes you have some knowledge of the underlying architecture for access-control within Spring Security. If you don`t you can skip it and come back to it later, as this section is only really relevant for people who need to do some customization in order to use more than simple role-based security.</p>
                    </div>
                    <div class="paragraph">
                        <p>When you use a namespace configuration, a default instance of <code>AccessDecisionManager</code> is automatically registered for you and will be used for making access decisions for method invocations and web URL access, based on the access attributes you specify in your <code>intercept-url</code> and <code>protect-pointcut</code> declarations (and in annotations if you are using annotation secured methods).</p>
                    </div>
                    <div class="paragraph">
                        <p>The default strategy is to use an <code>AffirmativeBased</code> <code>AccessDecisionManager</code> with a <code>RoleVoter</code> and an <code>AuthenticatedVoter</code>. You can find out more about these in the chapter on <a href="#authz-arch">authorization</a>.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="ns-custom-access-mgr"><a class="anchor" href="#ns-custom-access-mgr"></a>4.5.1. Customizing the AccessDecisionManager</h4>
                        <div class="paragraph">
                            <p>If you need to use a more complicated access control strategy then it is easy to set an alternative for both method and web security.</p>
                        </div>
                        <div class="paragraph">
                            <p>For method security, you do this by setting the <code>access-decision-manager-ref</code> attribute on <code>global-method-security</code> to the <code>id</code> of the appropriate <code>AccessDecisionManager</code> bean in the application context:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;global-method-security access-decision-manager-ref="myAccessDecisionManagerBean"&gt;
  ...
&lt;/global-method-security&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The syntax for web security is the same, but on the <code>http</code> element:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http access-decision-manager-ref="myAccessDecisionManagerBean"&gt;
  ...
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ns-auth-manager"><a class="anchor" href="#ns-auth-manager"></a>4.6. 认证管理器和命名空间</h3>
                    <div class="paragraph">
                        <p>在Spring Security中提供认证服务的主接口是<code>AuthenticationManager</code>。
                            它通常是Spring Security的<code>ProviderManager</code>类的实例，如果你之前已经试用过框架，那么你也许已经对它非常熟悉了。
                            如果不是，那么在技术概览章节汇中后面将会改变。
                            通过使用<code>authentication-manager</code>命名空间元素，bean被注册成实例。
                            如果你正在通过命名空间使用HTTP或者方法安全， 你是不能使用自定义的<code>AuthenticationManager</code>的，
                            但这不是一个问题，因为你能完全控制<code>AuthenticationProvider</code>的使用。</p>
                    </div>
                    <div class="paragraph">
                        <p>You may want to register additional <code>AuthenticationProvider</code> beans with the <code>ProviderManager</code> and you can do this using the <code>&lt;authentication-provider&gt;</code> element with the <code>ref</code> attribute, where the value of the attribute is the name of the provider bean you want to add. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;authentication-manager&gt;
  &lt;authentication-provider ref="casAuthenticationProvider"/&gt;
&lt;/authentication-manager&gt;

&lt;bean id="casAuthenticationProvider"
    class="org.springframework.security.cas.authentication.CasAuthenticationProvider"&gt;
  ...
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Another common requirement is that another bean in the context may require a reference to the <code>AuthenticationManager</code>. You can easily register an alias for the <code>AuthenticationManager</code> and use this name elsewhere in your application context.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;security:authentication-manager alias="authenticationManager"&gt;
   ...
&lt;/security:authentication-manager&gt;

&lt;bean id="customizedFormLoginFilter"
      class="com.somecompany.security.web.CustomFormLoginFilter"&gt;
   &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
   ...
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="sample-apps"><a class="anchor" href="#sample-apps"></a>5. 例子应用程序</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>There are several sample web applications that are available with the project. To avoid an overly large download, only the "tutorial" and "contacts" samples are included in the distribution zip file. The others can be built directly from the source which you can obtain as described in <a href="#get-source">the introduction</a>. It`s easy to build the project yourself and there`s more information on the project web site at <a href="http://spring.io/spring-security/">http://spring.io/spring-security/</a>. All paths referred to in this chapter are relative to the project source directory.</p>
                </div>
                <div class="sect2">
                    <h3 id="tutorial-sample"><a class="anchor" href="#tutorial-sample"></a>5.1. Tutorial Sample</h3>
                    <div class="paragraph">
                        <p>The tutorial sample is a nice basic example to get you started. It uses simple namespace configuration throughout. The compiled application is included in the distribution zip file, ready to be deployed into your web container (<code>spring-security-samples-tutorial-3.1.x.war</code>). The <a href="#ns-form-and-basic">form-based</a> authentication mechanism is used in combination with the commonly-used <a href="#remember-me">remember-me</a> authentication provider to automatically remember the login using cookies.</p>
                    </div>
                    <div class="paragraph">
                        <p>We recommend you start with the tutorial sample, as the XML is minimal and easy to follow. Most importantly, you can easily add this one XML file (and its corresponding <code>web.xml</code> entries) to your existing application. Only when this basic integration is achieved do we suggest you attempt adding in method authorization or domain object security.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="contacts-sample"><a class="anchor" href="#contacts-sample"></a>5.2. Contacts</h3>
                    <div class="paragraph">
                        <p>The Contacts Sample is an advanced example in that it illustrates the more powerful features of domain object access control lists (ACLs) in addition to basic application security. The application provides an interface with which the users are able to administer a simple database of contacts (the domain objects).</p>
                    </div>
                    <div class="paragraph">
                        <p>To deploy, simply copy the WAR file from Spring Security distribution into your container`s <code>webapps</code> directory. The war should be called <code>spring-security-samples-contacts-3.1.x.war</code> (the appended version number will vary depending on what release you are using).</p>
                    </div>
                    <div class="paragraph">
                        <p>After starting your container, check the application can load. Visit <a href="http://localhost:8080/contacts">http://localhost:8080/contacts</a> (or whichever URL is appropriate for your web container and the WAR you deployed).</p>
                    </div>
                    <div class="paragraph">
                        <p>Next, click "Debug". You will be prompted to authenticate, and a series of usernames and passwords are suggested on that page. Simply authenticate with any of these and view the resulting page. It should contain a success message similar to the following:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre>
Security Debug Information

Authentication object is of type:
org.springframework.security.authentication.UsernamePasswordAuthenticationToken

Authentication object as a String:

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@1f127853:
Principal: org.springframework.security.core.userdetails.User@b07ed00: Username: rod; \
Password: [PROTECTED]; Enabled: true; AccountNonExpired: true;
credentialsNonExpired: true; AccountNonLocked: true; \
Granted Authorities: ROLE_SUPERVISOR, ROLE_USER; \
Password: [PROTECTED]; Authenticated: true; \
Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: \
RemoteIpAddress: 127.0.0.1; SessionId: 8fkp8t83ohar; \
Granted Authorities: ROLE_SUPERVISOR, ROLE_USER

Authentication object holds the following granted authorities:

ROLE_SUPERVISOR (getAuthority(): ROLE_SUPERVISOR)
ROLE_USER (getAuthority(): ROLE_USER)

Success! Your web filters appear to be properly configured!
</pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Once you successfully receive the above message, return to the sample application`s home page and click "Manage". You can then try out the application. Notice that only the contacts available to the currently logged on user are displayed, and only users with <code>ROLE_SUPERVISOR</code> are granted access to delete their contacts. Behind the scenes, the <code>MethodSecurityInterceptor</code> is securing the business objects.</p>
                    </div>
                    <div class="paragraph">
                        <p>The application allows you to modify the access control lists associated with different contacts. Be sure to give this a try and understand how it works by reviewing the application context XML files.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ldap-sample"><a class="anchor" href="#ldap-sample"></a>5.3. LDAP Sample</h3>
                    <div class="paragraph">
                        <p>The LDAP sample application provides a basic configuration and sets up both a namespace configuration and an equivalent configuration using traditional beans, both in the same application context file. This means there are actually two identical authentication providers configured in this application.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="openid-sample"><a class="anchor" href="#openid-sample"></a>5.4. OpenID Sample</h3>
                    <div class="paragraph">
                        <p>The OpenID sample demonstrates how to use the namespace to configure OpenID and how to set up <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html">attribute exchange</a> configurations for Google, Yahoo and MyOpenID identity providers (you can experiment with adding others if you wish). It uses the JQuery-based <a href="http://code.google.com/p/openid-selector/">openid-selector</a> project to provide a user-friendly login page which allows the user to easily select a provider, rather than typing in the full OpenID identifier.</p>
                    </div>
                    <div class="paragraph">
                        <p>The application differs from normal authentication scenarios in that it allows any user to access the site (provided their OpenID authentication is successful). The first time you login, you will get a "Welcome [your name]"" message. If you logout and log back in (with the same OpenID identity) then this should change to "Welcome Back". This is achieved by using a custom <code>UserDetailsService</code> which assigns a standard role to any user and stores the identities internally in a map. Obviously a real application would use a database instead. Have a look at the source form more information. This class also takes into account the fact that different attributes may be returned from different providers and builds the name with which it addresses the user accordingly.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="cas-sample"><a class="anchor" href="#cas-sample"></a>5.5. CAS Sample</h3>
                    <div class="paragraph">
                        <p>The CAS sample requires that you run both a CAS server and CAS client. It isn`t included in the distribution so you should check out the project code as described in <a href="#get-source">the introduction</a>. You`ll find the relevant files under the <code>sample/cas</code> directory. There`s also a <code>Readme.txt</code> file in there which explains how to run both the server and the client directly from the source tree, complete with SSL support.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jaas-sample"><a class="anchor" href="#jaas-sample"></a>5.6. JAAS Sample</h3>
                    <div class="paragraph">
                        <p>The JAAS sample is very simple example of how to use a JAAS LoginModule with Spring Security. The provided LoginModule will successfully authenticate a user if the username equals the password otherwise a LoginException is thrown. The AuthorityGranter used in this example always grants the role ROLE_USER. The sample application also demonstrates how to run as the JAAS Subject returned by the LoginModule by setting <a href="#nsa-http-jaas-api-provision">jaas-api-provision</a> equal to "true".</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="preauth-sample"><a class="anchor" href="#preauth-sample"></a>5.7. Pre-Authentication Sample</h3>
                    <div class="paragraph">
                        <p>This sample application demonstrates how to wire up beans from the <a href="#preauth">pre-authentication</a> framework to make use of login information from a Java EE container. The user name and roles are those setup by the container.</p>
                    </div>
                    <div class="paragraph">
                        <p>The code is in <code>samples/preauth</code>.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="community"><a class="anchor" href="#community"></a>6. Spring Security Community</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="jira"><a class="anchor" href="#jira"></a>6.1. Issue Tracking</h3>
                    <div class="paragraph">
                        <p>Spring Security uses JIRA to manage bug reports and enhancement requests. If you find a bug, please log a report using JIRA. Do not log it on the support forum, mailing list or by emailing the project`s developers. Such approaches are ad-hoc and we prefer to manage bugs using a more formal process.</p>
                    </div>
                    <div class="paragraph">
                        <p>If possible, in your issue report please provide a JUnit test that demonstrates any incorrect behaviour. Or, better yet, provide a patch that corrects the issue. Similarly, enhancements are welcome to be logged in the issue tracker, although we only accept enhancement requests if you include corresponding unit tests. This is necessary to ensure project test coverage is adequately maintained.</p>
                    </div>
                    <div class="paragraph">
                        <p>You can access the issue tracker at <a href="http://jira.springsource.org/browse/SEC">http://jira.springsource.org/browse/SEC</a>.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="becoming-involved"><a class="anchor" href="#becoming-involved"></a>6.2. Becoming Involved</h3>
                    <div class="paragraph">
                        <p>We welcome your involvement in the Spring Security project. There are many ways of contributing, including reading the forum and responding to questions from other people, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, or simply making suggestions.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="further-info"><a class="anchor" href="#further-info"></a>6.3. 进一步信息</h3>
                    <div class="paragraph">
                        <p>Questions and comments on Spring Security are welcome. You can use the Spring Community Forum web site at <a href="http://forum.springsource.org">http://forum.springsource.org</a> to discuss Spring Security with other users of the framework. Remember to use JIRA for bug reports, as explained above.</p>
                    </div>
                </div>
            </div>
        </div>
        <h1 id="overall-architecture" class="sect0"><a class="anchor" href="#overall-architecture"></a>架构和实现</h1>
        <div class="paragraph">
            <p>一旦你熟悉设置和运行几个基于命名空间配置的应用程序，你也许会希望进一步理解关于框架命名空间正面背后的实际运作。
                像大多数软件那样，Spring Security一定会有核心接口、类还有抽象概念，这些东西在框架中到处被用到。
                在参考手册这个部分，我将会来看看这些东西，并且看看他们在支持Spring Security的认证和访问控制方面，是如何在一起工作的。</p>
        </div>
        <div class="sect1">
            <h2 id="technical-overview"><a class="anchor" href="#technical-overview"></a>1. 技术概览</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="runtime-environment"><a class="anchor" href="#runtime-environment"></a>1.1. 运行环境</h3>
                    <div class="paragraph">
                        <p>Spring Security 3.0需要Java 5.0的运行环境或者更高版本。
                            Spring Security旨在独立的容器内运行，不需要放置任何特定配置文件到你的JRE中。
                            特别地，不需要配置一个特定的Java认证和授权服务（JAAS）策略文件或者放置Spring Security到公共classpath路径下。</p>
                    </div>
                    <div class="paragraph">
                        <p>相似的，如果你在使用EJB容器或者Servlet容器，那么你不需要放置任何配置文件到哪里， 也不需要将Spring Security加入到服务器的类加载器中。
                            所有必需的文件都将被包含在您的应用程序里。</p>
                    </div>
                    <div class="paragraph">
                        <p>这个设计提供了最大的部署时间的灵活性，你可以简单地复制你的目标文件（可以是JAR，WAR或EAR）从一个系统到另一个，它会立即开始工作。</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="core-components"><a class="anchor" href="#core-components"></a>1.2. 核心组件</h3>
                    <div class="paragraph">
                        <p>在Spring Security 3.0中，<code>spring-security-core</code>jar的内容被精简到最低限度。
                            它不再包含与web应用安全，LDAP或命名空间配置的任何代码。
                            我们来看看一些Java类型，这些你会核心模块中找到。
                            它们代表了框架的基石，因此，如果你需要超越简单的命名空间配置的话，那么，你了解它们是什么，即使你实际上并不需要直接与他们打交道，但任然是很重要的。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="securitycontextholder-securitycontext-and-authentication-objects"><a class="anchor" href="#securitycontextholder-securitycontext-and-authentication-objects"></a>1.2.1. SecurityContextHolder, SecurityContext和Authentication Objects</h4>
                        <div class="paragraph">
                            <p>最基本的对象是<code>SecurityContextHolder</code>。
                                这是我们存储当前security context的应用程序的详情，其中包括当前正在使用的应用程序的主要的详情。
                                默认情况下，<code>SecurityContextHolder</code>中使用一个  <code>ThreadLocal</code> 存储这些详情，
                                这意味着，该security的上下文总是可用来在执行的同一个线程的方法，即使security context未明确的作为参数传递到那些方法。
                                使用<code>ThreadLocal</code>的这种方式，如果小心清除处理完请求后的当前主要的线程，是相当安全。
                                当然，Spring Security为你自动的处理这个，所以没有必要担心。</p>
                        </div>
                        <div class="paragraph">
                            <p>有些程序并不完全适合使用一个 <code>ThreadLocal</code> 的，因为它们处理线程的特殊方式。
                                例如，Swing客户端可能希望在Java虚拟机中所有线程使用相同的security context。
                                <code>SecurityContextHolder</code> 可以在启动时的策略进行配置，以指定您希望如何被存储在上下文中。
                                对于一个独立的应用程序，你可以使用 <code>SecurityContextHolder.MODE_GLOBAL</code> 策略。
                                其他应用程序可能希望由安全线程产生的线程也采用同样的安全标识。
                                这是通过使用 <code>SecurityContextHolder.MODE_INHERITABLETHREADLOCAL</code>实现。
                                您可以通过两种方式更改默认模式 <code>SecurityContextHolder.MODE_THREADLOCAL</code>。
                                第一种，是设置系统属性，第二种，是调用静态方法 <code>SecurityContextHolder</code>。
                                大多数应用程序不需要更改默认，但如果你要这样做，看看关于 <code>SecurityContextHolder</code> 的JavaDocs,来了解更多信息。</p>
                        </div>
                        <div class="sect4">
                            <h5 id="obtaining-information-about-the-current-user"><a class="anchor" href="#obtaining-information-about-the-current-user"></a>获取当前用户信息</h5>
                            <div class="paragraph">
                                <p>在<code>SecurityContextHolder</code>中，我们存储了当前与应用程序交互的主要细节。
                                    Spring Security使用<code>Authentication</code>对象来表示这些信息的。
                                    你通常不需要自己创建一个<code>Authentication</code>对象，但用户查询 <code>Authentication</code> 对象是很常见的。
                                    在应用程序的任何地方- -您可以使用下面的代码块，以获得当前已验证用户的名称，例如：
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>通过调用getContext()方法返回的对象，是一个SecurityContext接口的实例。
                                    这是被保留在本地线程存储器中的对象。
                                    正如我们将在下面看到的，在Spring Security中大多数身份验证机制返回的是一个<code>UserDetails</code>的实例，作为主体（principal）。<br/>
                                    （译注：这里主体——principal，是我自己的理解。维基百科的解释是一个可以用作认证的实体，具有高度抽象的概念，可以是单个个人，也可以是计算机、服务等等。
                                    原文是这样的：“A principal in computer security is an entity that can be authenticated by a computer system or network.”）
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="tech-userdetailsservice"><a class="anchor" href="#tech-userdetailsservice"></a>1.2.2. UserDetailsService</h4>
                        <div class="paragraph">
                            <p>从上面的代码片段中需要注意的另一个问题是，你可以从<code>Authentication</code>对象获得一个主体。
                                <code>UserDetails</code> 是Spring Security的核心接口。 它代表了主体，但在一个可扩展的和特定应用的方式下。
                                想象一下<code>UserDetails</code>，在你的用户数据库和那些Spring Security所需要包含在<code>SecurityContextHolder</code>中的东西之间，当作适配器。
                                为了让你自己的用户数据呈现出来， 你会经常会将<code>UserDetails</code>转换成你的应用程序所提供的原始对象，
                                这样你就可以调用业务相关的方法（如getEmail()，getEmployeeNumber()等）。</p>
                        </div>
                        <div class="paragraph">
                            <p>现在你可能想知道，那就是，什么时候该我提供一个 <code>UserDetails</code> 对象呢？又怎样提供？
                                我想你是说如何声明这个对象，再有就是，我不需要写任何Java代码-这是怎么回事？
                                简短的回答是，这里有一个叫做<code>UserDetailsService</code>特殊的接口。
                                这个接口中唯一方法，它接受一个用户名为字符串类型的参数，同时返回一个<code>UserDetails</code>对象:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>
  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>这是使用Spring Security加载用户信息最常用的方法，还有，你会看到它被使用到整个框架中，每当需要用户信息的时候。</p>
                        </div>
                        <div class="paragraph">
                            <p>在一个成功的认证中，<code>UserDetails</code>被用于构建<code>Authentication</code>对象，
                                它是存储在<code>SecurityContextHolder</code>中的（详见<a href="#tech-intro-authentication">下文</a>）。
                                好消息是，我们提供了大量的UserDetailsService实现，其中一个使用内存映射（<code>InMemoryDaoImpl</code>），
                                另一个使用JDBC（<code>JdbcDaoImpl</code>）。
                                大部分用户倾向于他们自己编写，然而，
                                把他们自己的实现常常放到现有数据访问对象（DAO）继承层次的顶部，DAO代表的是员工，客户或应用程序的其他用户的。
                                请记住这个优点，那就是无论你的<code>UserDetailsService</code>返回什么，都能使用上面代码片段从<code>SecurityContextHolder</code>中获取到。
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>关于<code>UserDetailsService</code>常常会有些混淆的地方。
                                                它纯粹是用于用户数据的DAO和执行仅此而已的功能，而不是在框架内提供数据到其他组件。
                                                特别说明，它<em>不</em>认证用户，而是由<code>AuthenticationManager</code>负责的。
                                                在许多情况下，如果你需要一个自定义的验证过程，<a href="#core-services-authentication-manager">直接实现 <code>AuthenticationProvider</code></a>更有意义。</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="tech-granted-authority"><a class="anchor" href="#tech-granted-authority"></a>1.2.3. GrantedAuthority</h4>
                        <div class="paragraph">
                            <p>除了主体，另外一个由<code>Authentication</code>提供的重要方法是<code>getAuthorities()</code>。
                                这个方法提供了一组<code>GrantedAuthority</code>对象。
                                不出意外的话，<code>GrantedAuthority</code>是已经授予给主体的权限。
                                这些权限通常是“角色”，如 <code>ROLE_ADMINISTRATOR</code>  或 <code>ROLE_HR_SUPERVISOR</code> 。
                                这些角色稍后将会为网络授权，方法授权和领域对象授权而配置。
                                Spring Security的其他部分能够解释这些权限，并期望他们出现。
                                <code>GrantedAuthority</code>对象通常是由<code>UserDetailsService</code>加载的。</p>
                        </div>
                        <div class="paragraph">
                            <p>通常<code>GrantedAuthority</code>对象是应用范围的权限。
                                他们不是针对指定的域对象。这样，你就不可能拥有 <code>GrantedAuthority</code> 来表示一个编号为54的员工对象的权限，
                                因为如果有成千上万的这种授权，你会很快耗尽内存（或者，最起码，导致应用程序需要很长的时间去验证一个用户）。
                                当然，Spring Security被明确地设计出来处理这类常见需求，但是你最好别为这个目的，而使用这项目的领域模型安全功能。</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="summary"><a class="anchor" href="#summary"></a>1.2.4. 总结</h4>
                        <div class="paragraph">
                            <p>只是为了回顾一下，我们到目前为止看到的Spring Security的主要组成部分有：</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><code>SecurityContextHolder</code>, 提供访问<code>SecurityContext</code>。</p>
                                </li>
                                <li>
                                    <p><code>SecurityContext</code>, 控制<code>Authentication</code> 和请求对应的安全信息。</p>
                                </li>
                                <li>
                                    <p><code>Authentication</code>, 代表了在Spring Security的特定方式的主体。</p>
                                </li>
                                <li>
                                    <p><code>GrantedAuthority</code>, 反映了在应用范围内授予给主体的权限。</p>
                                </li>
                                <li>
                                    <p><code>UserDetails</code>, 提供必要的信息，比如，从您的应用DAO或其他的安全数据来源中构建一个验证对象。</p>
                                </li>
                                <li>
                                    <p><code>UserDetailsService</code>, 当传入一个<code>String</code>的用户名（或者证书ID 或者类似的）时候，创建一个<code>UserDetails</code>。</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>现在，你应该对这些重用组件有一定理解了，下面让我们在认证处理环节中一探究竟。
                                Now that you`ve gained an understanding of these repeatedly-used components, let`s take a closer look at the process of authentication.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="tech-intro-authentication"><a class="anchor" href="#tech-intro-authentication"></a>1.3. 身份认证</h3>
                    <div class="paragraph">
                        <p>Spring Security可以加入很多不同的验证环境。
                            虽然我们推荐人们使用Spring Security进行认证，而不是与现有的容器管理认证系统整合，但它也是支持的 - 使用你自己的属性验证系统进行整合。</p>
                    </div>
                    <div class="sect3">
                        <h4 id="what-is-authentication-in-spring-security"><a class="anchor" href="#what-is-authentication-in-spring-security"></a>1.3.1. 什么是Spring Security认证？</h4>
                        <div class="paragraph">
                            <p>让我们考虑一个大家都很熟悉的标准的认证场景。</p>
                        </div>
                        <div class="olist arabic">
                            <ol class="arabic">
                                <li>
                                    <p>用户被提示输入用户名和密码进行登录。A user is prompted to log in with a username and password.</p>
                                </li>
                                <li>
                                    <p>该系统（成功）验证该用户名的密码是正确的。</p>
                                </li>
                                <li>
                                    <p>获取到该用户的上下文信息（其角色列表等）。</p>
                                </li>
                                <li>
                                    <p>为用户建立安全上下文。</p>
                                </li>
                                <li>
                                    <p>用户处理，有可能执行一些操作是可能被用于检查所需的权限，对当前安全上下文信息操作的访问控制机制的保护。</p>
                                </li>
                            </ol>
                        </div>
                        <div class="paragraph">
                            <p>前三项构成了验证过程，所以我们就来看看这些都是如何在Spring Security的范围内进行。</p>
                        </div>
                        <div class="olist arabic">
                            <ol class="arabic">
                                <li>
                                    <p>用户名和密码获取到并组合成的一个<code>UsernamePasswordAuthenticationToken</code>的实例（一个<code>Authentication</code>界面的，我们前面看到的）</p>
                                </li>
                                <li>
                                    <p>令牌被传递到 <code>AuthenticationManager</code>的实例进行验证。</p>
                                </li>
                                <li>
                                    <p>在一个成功的认证中，<code>AuthenticationManager</code>返回一个完整的<code>Authentication</code>实例。</p>
                                </li>
                                <li>
                                    <p>security context的建立是通过调用<code>SecurityContextHolder.getContext().setAuthentication(...)</code>，
                                        传入返回的认证对象。</p>
                                </li>
                            </ol>
                        </div>
                        <div class="paragraph">
                            <p>从这一点上，用户被认为是要被认证。让我们来看看一些代码作为一个例子。   </p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class AuthenticationExample {
  private static AuthenticationManager am = new SampleAuthenticationManager();

  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    while(true) {
      System.out.println("Please enter your username:");
      String name = in.readLine();
      System.out.println("Please enter your password:");
      String password = in.readLine();
      try {
        Authentication request = new UsernamePasswordAuthenticationToken(name, password);
        Authentication result = am.authenticate(request);
        SecurityContextHolder.getContext().setAuthentication(result);
        break;
      } catch(AuthenticationException e) {
        System.out.println("Authentication failed: " + e.getMessage());
      }
    }
    System.out.println("Successfully authenticated. Security context contains: " +
              SecurityContextHolder.getContext().getAuthentication());
  }
}

class SampleAuthenticationManager implements AuthenticationManager {
  static final List&lt;GrantedAuthority&gt; AUTHORITIES = new ArrayList&lt;GrantedAuthority&gt;();

  static {
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
  }

  public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth.getName().equals(auth.getCredentials())) {
      return new UsernamePasswordAuthenticationToken(auth.getName(),
        auth.getCredentials(), AUTHORITIES);
      }
      throw new BadCredentialsException("Bad Credentials");
  }
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>在这里，我们写了一个小程序，要求用户输入用户名和密码，进行上述顺序。
                                我们在<code>AuthenticationManager</code>这里实现了，将要验证任意用户的用户名和密码是否相同的。
                                它分配每一个用户的一个角色。根据上面的代码，输出将是这样的：</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint txt language-txt"><code>
Please enter your username:
bob
Please enter your password:
password
Authentication failed: Bad Credentials
Please enter your username:
bob
Please enter your password:
bob
Successfully authenticated. Security context contains: \
 org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230: \
 Principal: bob; Password: [PROTECTED]; \
 Authenticated: true; Details: null; \
 Granted Authorities: ROLE_USER
</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>请注意，您通常不需要写任何这样的代码。
                                这个过程通常会发生在内部，比如在Web认证过滤器中。
                                我们刚刚在这里展现代码的，是要说明，在Spring Security中，究竟是什么构成了认证这样的一个问题，有一个相当简单的答案。
                                当用户通过身份验证， <code>SecurityContextHolder</code> 中包含就一个完全填充的 <code>Authentication</code> 对象。</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="setting-the-securitycontextholder-contents-directly"><a class="anchor" href="#setting-the-securitycontextholder-contents-directly"></a>1.3.2. 直接设置SecurityContextHolder的内容</h4>
                        <div class="paragraph">
                            <p>实际上，Spring Security并不关心你是如何将 <code>Authentication</code>对象放入<code>SecurityContextHolder</code>中的。
                                唯一的关键要求是，<code>SecurityContextHolder</code>需要包含一个<code>Authentication</code>，
                                它代表一个主体在<code>AbstractSecurityInterceptor</code>之前（我们会在后面看到更多）需要验证用户操作。</p>
                        </div>
                        <div class="paragraph">
                            <p>你可以（）
                                You can (and many users do) write their own filters or MVC controllers to provide interoperability with authentication systems
                                that are not based on Spring Security.
                                For example, you might be using Container-Managed Authentication which makes the current user available from a ThreadLocal or JNDI location.
                                Or you might work for a company that has a legacy proprietary authentication system, which is a corporate "standard" over which you have little control.
                                In situations like this it`s quite easy to get Spring Security to work, and still provide authorization capabilities.
                                All you need to do is write a filter (or equivalent) that reads the third-party user information from a location,
                                build a Spring Security-specific <code>Authentication</code> object, and put it into the <code>SecurityContextHolder</code>.
                                In this case you also need to think about things which are normally taken care of automatically by the built-in authentication infrastructure.
                                For example, you might need to pre-emptively create an HTTP session to <a href="#tech-intro-sec-context-persistence">cache the context between requests</a>,
                                before you write the response to the client <span class="footnote">[<a id="_footnoteref_7" class="footnote" href="#_footnote_7" title="View footnote.">7</a>]</span>.</p>
                        </div>
                        <div class="paragraph">
                            <p>If you`re wondering how the <code>AuthenticationManager</code> is implemented in a real world example,
                                we`ll look at that in the <a href="#core-services-authentication-manager">core services chapter</a>.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="tech-intro-web-authentication"><a class="anchor" href="#tech-intro-web-authentication"></a>1.4. 在web应用中的认证</h3>
                    <div class="paragraph">
                        <p>Now let`s explore the situation where you are using Spring Security in a web application (without <code>web.xml</code> security enabled).
                            How is a user authenticated and the security context established?</p>
                    </div>
                    <div class="paragraph">
                        <p>Consider a typical web application`s authentication process:</p>
                    </div>
                    <div class="olist arabic">
                        <ol class="arabic">
                            <li>
                                <p>You visit the home page, and click on a link.</p>
                            </li>
                            <li>
                                <p>A request goes to the server, and the server decides that you`ve asked for a protected resource.</p>
                            </li>
                            <li>
                                <p>As you`re not presently authenticated, the server sends back a response indicating that you must authenticate. The response will either be an HTTP response code, or a redirect to a particular web page.</p>
                            </li>
                            <li>
                                <p>Depending on the authentication mechanism, your browser will either redirect to the specific web page so that you can fill out the form, or the browser will somehow retrieve your identity (via a BASIC authentication dialogue box, a cookie, a X.509 certificate etc.).</p>
                            </li>
                            <li>
                                <p>The browser will send back a response to the server. This will either be an HTTP POST containing the contents of the form that you filled out, or an HTTP header containing your authentication details.</p>
                            </li>
                            <li>
                                <p>Next the server will decide whether or not the presented credentials are valid. If they`re valid, the next step will happen. If they`re invalid, usually your browser will be asked to try again (so you return to step two above).</p>
                            </li>
                            <li>
                                <p>The original request that you made to cause the authentication process will be retried. Hopefully you`ve authenticated with sufficient granted authorities to access the protected resource. If you have sufficient access, the request will be successful. Otherwise, you`ll receive back an HTTP error code 403, which means "forbidden".</p>
                            </li>
                        </ol>
                    </div>
                    <div class="paragraph">
                        <p>Spring Security has distinct classes responsible for most of the steps described above. The main participants (in the order that they are used) are the <code>ExceptionTranslationFilter</code>, an <code>AuthenticationEntryPoint</code> and an "authentication mechanism", which is responsible for calling the <code>AuthenticationManager</code> which we saw in the previous section.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="exceptiontranslationfilter"><a class="anchor" href="#exceptiontranslationfilter"></a>1.4.1. ExceptionTranslationFilter</h4>
                        <div class="paragraph">
                            <p><code>ExceptionTranslationFilter</code> is a Spring Security filter that has responsibility for detecting any Spring Security exceptions that are thrown. Such exceptions will generally be thrown by an <code>AbstractSecurityInterceptor</code>, which is the main provider of authorization services. We will discuss <code>AbstractSecurityInterceptor</code> in the next section, but for now we just need to know that it produces Java exceptions and knows nothing about HTTP or how to go about authenticating a principal. Instead the <code>ExceptionTranslationFilter</code> offers this service, with specific responsibility for either returning error code 403 (if the principal has been authenticated and therefore simply lacks sufficient access - as per step seven above), or launching an <code>AuthenticationEntryPoint</code> (if the principal has not been authenticated and therefore we need to go commence step three).</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="tech-intro-auth-entry-point"><a class="anchor" href="#tech-intro-auth-entry-point"></a>1.4.2. AuthenticationEntryPoint</h4>
                        <div class="paragraph">
                            <p>The <code>AuthenticationEntryPoint</code> is responsible for step three in the above list. As you can imagine, each web application will have a default authentication strategy (well, this can be configured like nearly everything else in Spring Security, but let`s keep it simple for now). Each major authentication system will have its own <code>AuthenticationEntryPoint</code> implementation, which typically performs one of the actions described in step 3.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="authentication-mechanism"><a class="anchor" href="#authentication-mechanism"></a>1.4.3. 认证机制</h4>
                        <div class="paragraph">
                            <p>Once your browser submits your authentication credentials (either as an HTTP form post or HTTP header) there needs to be something on the server that"collects" these authentication details. By now we`re at step six in the above list. In Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism". Examples are form-base login and Basic authentication. Once the authentication details have been collected from the user agent, an <code>Authentication</code>"request" object is built and then presented to the <code>AuthenticationManager</code>.</p>
                        </div>
                        <div class="paragraph">
                            <p>After the authentication mechanism receives back the fully-populated <code>Authentication</code> object, it will deem the request valid, put the <code>Authentication</code> into the <code>SecurityContextHolder</code>, and cause the original request to be retried (step seven above). If, on the other hand, the <code>AuthenticationManager</code> rejected the request, the authentication mechanism will ask the user agent to retry (step two above).</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="tech-intro-sec-context-persistence"><a class="anchor" href="#tech-intro-sec-context-persistence"></a>1.4.4. 在请求间存储SecurityContext</h4>
                        <div class="paragraph">
                            <p>Depending on the type of application, there may need to be a strategy in place to store the security context between user operations. In a typical web application, a user logs in once and is subsequently identified by their session Id. The server caches the principal information for the duration session. In Spring Security, the responsibility for storing the <code>SecurityContext</code> between requests falls to the <code>SecurityContextPersistenceFilter</code>, which by default stores the context as an <code>HttpSession</code> attribute between HTTP requests. It restores the context to the <code>SecurityContextHolder</code> for each request and, crucially, clears the <code>SecurityContextHolder</code> when the request completes. You shouldn`t interact directly with the <code>HttpSession</code> for security purposes. There is simply no justification for doing so - always use the <code>SecurityContextHolder</code> instead.</p>
                        </div>
                        <div class="paragraph">
                            <p>Many other types of application (for example, a stateless RESTful web service) do not use HTTP sessions and will re-authenticate on every request. However, it is still important that the <code>SecurityContextPersistenceFilter</code> is included in the chain to make sure that the <code>SecurityContextHolder</code> is cleared after each request.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>In an application which receives concurrent requests in a single session,
                                                the same <code>SecurityContext</code> instance will be shared between threads.
                                                Even though a <code>ThreadLocal</code> is being used, it is the same instance that is retrieved from the <code>HttpSession</code> for each thread.
                                                This has implications if you wish to temporarily change the context under which a thread is running.
                                                If you just use <code>SecurityContextHolder.getContext()</code>, and call <code>setAuthentication(anAuthentication)</code> on the returned context object,
                                                then the <code>Authentication</code> object will change in <em>all</em> concurrent threads which share the same <code>SecurityContext</code> instance.
                                                You can customize the behaviour of <code>SecurityContextPersistenceFilter</code> to create a completely new <code>SecurityContext</code> for each request,
                                                preventing changes in one thread from affecting another.
                                                Alternatively you can create a new instance just at the point where you temporarily change the context.
                                                The method <code>SecurityContextHolder.createEmptyContext()</code> always returns a new context instance.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="tech-intro-access-control"><a class="anchor" href="#tech-intro-access-control"></a>1.5.Spring Security的访问控制(授权)</h3>
                    <div class="paragraph">
                        <p>Spring Security中访问控制的主接口是<code>AccessDecisionManager</code>，它的责任是为访问控制做决策。
                            它有一个<code>decide</code>方法，它带有一个<code>Authentication</code>对象，代表主体的请求访问，
                            一个“安全对象”（见下文）和一个安全元数据应用到对象的属性队列（比如，需要被授权访问的角色列表）。

                            It has a <code>decide</code> method which takes an <code>Authentication</code> object representing the principal requesting access,
                            a "secure object" (see below) and a list of security metadata attributes which apply for the object
                            (such as a list of roles which are required for access to be granted).</p>
                    </div>
                    <div class="sect3">
                        <h4 id="security-and-aop-advice"><a class="anchor" href="#security-and-aop-advice"></a>1.5.1. Security and AOP Advice</h4>
                        <div class="paragraph">
                            <p>If you`re familiar with AOP, you`d be aware there are different types of advice available: before, after, throws and around. An around advice is very useful, because an advisor can elect whether or not to proceed with a method invocation, whether or not to modify the response, and whether or not to throw an exception. Spring Security provides an around advice for method invocations as well as web requests. We achieve an around advice for method invocations using Spring`s standard AOP support and we achieve an around advice for web requests using a standard Filter.</p>
                        </div>
                        <div class="paragraph">
                            <p>For those not familiar with AOP, the key point to understand is that Spring Security can help you protect method invocations as well as web requests. Most people are interested in securing method invocations on their services layer. This is because the services layer is where most business logic resides in current-generation Java EE applications. If you just need to secure method invocations in the services layer, Spring`s standard AOP will be adequate. If you need to secure domain objects directly, you will likely find that AspectJ is worth considering.</p>
                        </div>
                        <div class="paragraph">
                            <p>You can elect to perform method authorization using AspectJ or Spring AOP, or you can elect to perform web request authorization using filters. You can use zero, one, two or three of these approaches together. The mainstream usage pattern is to perform some web request authorization, coupled with some Spring AOP method invocation authorization on the services layer.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="secure-objects"><a class="anchor" href="#secure-objects"></a>1.5.2. Secure Objects and the AbstractSecurityInterceptor</h4>
                        <div class="paragraph">
                            <p>So what <em>is</em> a "secure object" anyway? Spring Security uses the term to refer to any object that can have security (such as an authorization decision) applied to it. The most common examples are method invocations and web requests.</p>
                        </div>
                        <div class="paragraph">
                            <p>Each supported secure object type has its own interceptor class, which is a subclass of <code>AbstractSecurityInterceptor</code>. Importantly, by the time the <code>AbstractSecurityInterceptor</code> is called, the <code>SecurityContextHolder</code> will contain a valid <code>Authentication</code> if the principal has been authenticated.</p>
                        </div>
                        <div class="paragraph">
                            <p><code>AbstractSecurityInterceptor</code> provides a consistent workflow for handling secure object requests, typically:</p>
                        </div>
                        <div class="olist arabic">
                            <ol class="arabic">
                                <li>
                                    <p>Look up the "configuration attributes" associated with the present request</p>
                                </li>
                                <li>
                                    <p>Submitting the secure object, current <code>Authentication</code> and configuration attributes to the <code>AccessDecisionManager</code> for an authorization decision</p>
                                </li>
                                <li>
                                    <p>Optionally change the <code>Authentication</code> under which the invocation takes place</p>
                                </li>
                                <li>
                                    <p>Allow the secure object invocation to proceed (assuming access was granted)</p>
                                </li>
                                <li>
                                    <p>Call the <code>AfterInvocationManager</code> if configured, once the invocation has returned. If the invocation raised an exception, the <code>AfterInvocationManager</code> will not be invoked.</p>
                                </li>
                            </ol>
                        </div>
                        <div class="sect4">
                            <h5 id="tech-intro-config-attributes"><a class="anchor" href="#tech-intro-config-attributes"></a>What are Configuration Attributes?</h5>
                            <div class="paragraph">
                                <p>A "configuration attribute" can be thought of as a String that has special meaning to the classes used by <code>AbstractSecurityInterceptor</code>. They are represented by the interface <code>ConfigAttribute</code> within the framework. They may be simple role names or have more complex meaning, depending on the how sophisticated the <code>AccessDecisionManager</code> implementation is. The <code>AbstractSecurityInterceptor</code> is configured with a <code>SecurityMetadataSource</code> which it uses to look up the attributes for a secure object. Usually this configuration will be hidden from the user. Configuration attributes will be entered as annotations on secured methods or as access attributes on secured URLs. For example, when we saw something like <code>&lt;intercept-url pattern='/secure/**' access='ROLE_A,ROLE_B'/&gt;</code> in the namespace introduction, this is saying that the configuration attributes <code>ROLE_A</code> and <code>ROLE_B</code> apply to web requests matching the given pattern. In practice, with the default <code>AccessDecisionManager</code> configuration, this means that anyone who has a <code>GrantedAuthority</code> matching either of these two attributes will be allowed access. Strictly speaking though, they are just attributes and the interpretation is dependent on the <code>AccessDecisionManager</code> implementation. The use of the prefix <code>ROLE_</code> is a marker to indicate that these attributes are roles and should be consumed by Spring Security`s`RoleVoter`. This is only relevant when a voter-based <code>AccessDecisionManager</code> is in use. We`ll see how the <code>AccessDecisionManager</code> is implemented in the <a href="#authz-arch">authorization chapter</a>.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="runasmanager"><a class="anchor" href="#runasmanager"></a>RunAsManager</h5>
                            <div class="paragraph">
                                <p>Assuming <code>AccessDecisionManager</code> decides to allow the request, the <code>AbstractSecurityInterceptor</code> will normally just proceed with the request. Having said that, on rare occasions users may want to replace the <code>Authentication</code> inside the <code>SecurityContext</code> with a different <code>Authentication</code>, which is handled by the <code>AccessDecisionManager</code> calling a <code>RunAsManager</code>. This might be useful in reasonably unusual situations, such as if a services layer method needs to call a remote system and present a different identity. Because Spring Security automatically propagates security identity from one server to another (assuming you`re using a properly-configured RMI or HttpInvoker remoting protocol client), this may be useful.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="afterinvocationmanager"><a class="anchor" href="#afterinvocationmanager"></a>AfterInvocationManager</h5>
                            <div class="paragraph">
                                <p>Following the secure object invocation proceeding and then returning - which may mean a method invocation completing or a filter chain proceeding - the <code>AbstractSecurityInterceptor</code> gets one final chance to handle the invocation. At this stage the <code>AbstractSecurityInterceptor</code> is interested in possibly modifying the return object. We might want this to happen because an authorization decision couldn`t be made "on the way in" to a secure object invocation. Being highly pluggable, <code>AbstractSecurityInterceptor</code> will pass control to an <code>AfterInvocationManager</code> to actually modify the object if needed. This class can even entirely replace the object, or throw an exception, or not change it in any way as it chooses. The after-invocation checks will only be executed if the invocation is successful. If an exception occurs, the additional checks will be skipped.</p>
                            </div>
                            <div class="paragraph">
                                <p><code>AbstractSecurityInterceptor</code> and its related objects are shown in <a href="#abstract-security-interceptor">Security interceptors and the "secure object" model</a></p>
                            </div>
                            <div id="abstract-security-interceptor" class="imageblock">
                                <div class="content">
                                    <img src="images/security-interception.png" alt="Abstract Security Interceptor">
                                </div>
                                <div class="title">Figure 1. Security interceptors and the "secure object" model</div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="extending-the-secure-object-model"><a class="anchor" href="#extending-the-secure-object-model"></a>Extending the Secure Object Model</h5>
                            <div class="paragraph">
                                <p>Only developers contemplating an entirely new way of intercepting and authorizing requests would need to use secure objects directly. For example, it would be possible to build a new secure object to secure calls to a messaging system. Anything that requires security and also provides a way of intercepting a call (like the AOP around advice semantics) is capable of being made into a secure object. Having said that, most Spring applications will simply use the three currently supported secure object types (AOP Alliance <code>MethodInvocation</code>, AspectJ <code>JoinPoint</code> and web request <code>FilterInvocation</code>) with complete transparency.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="localization"><a class="anchor" href="#localization"></a>1.6. 本地化</h3>
                    <div class="paragraph">
                        <p>Spring Security supports localization of exception messages that end users are likely to see. If your application is designed for English-speaking users, you don`t need to do anything as by default all Security Security messages are in English. If you need to support other locales, everything you need to know is contained in this section.</p>
                    </div>
                    <div class="paragraph">
                        <p>All exception messages can be localized, including messages related to authentication failures and access being denied (authorization failures). Exceptions and logging messages that are focused on developers or system deployers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) are not localized and instead are hard-coded in English within Spring Security`s code.</p>
                    </div>
                    <div class="paragraph">
                        <p>Shipping in the <code>spring-security-core-xx.jar</code> you will find an <code>org.springframework.security</code> package that in turn contains a <code>messages.properties</code> file, as well as localized versions for some common languages. This should be referred to by your`ApplicationContext`, as Spring Security classes implement Spring`s <code>MessageSourceAware</code> interface and expect the message resolver to be dependency injected at application context startup time. Usually all you need to do is register a bean inside your application context to refer to the messages. An example is shown below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt;
  &lt;property name="basename" value="classpath:org/springframework/security/messages"/&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The <code>messages.properties</code> is named in accordance with standard resource bundles and represents the default language supported by Spring Security messages. This default file is in English.</p>
                    </div>
                    <div class="paragraph">
                        <p>If you wish to customize the <code>messages.properties</code> file, or support other languages, you should copy the file, rename it accordingly, and register it inside the above bean definition. There are not a large number of message keys inside this file, so localization should not be considered a major initiative. If you do perform localization of this file, please consider sharing your work with the community by logging a JIRA task and attaching your appropriately-named localized version of <code>messages.properties</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>Spring Security relies on Spring`s localization support in order to actually lookup the appropriate message. In order for this to work, you have to make sure that the locale from the incoming request is stored in Spring`s <code>org.springframework.context.i18n.LocaleContextHolder</code>. Spring MVC`s <code>DispatcherServlet</code> does this for your application automatically, but since Spring Security`s filters are invoked before this, the <code>LocaleContextHolder</code> needs to be set up to contain the correct <code>Locale</code> before the filters are called. You can either do this in a filter yourself (which must come before the Spring Security filters in`web.xml`) or you can use Spring`s <code>RequestContextFilter</code>. Please refer to the Spring Framework documentation for further details on using localization with Spring.</p>
                    </div>
                    <div class="paragraph">
                        <p>The "contacts" sample application is set up to use localized messages.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="core-services"><a class="anchor" href="#core-services"></a>2. 核心服务</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Now that we have a high-level overview of the Spring Security architecture and its core classes, let`s take a closer look at one or two of the core interfaces and their implementations, in particular the <code>AuthenticationManager</code>, <code>UserDetailsService</code> and the <code>AccessDecisionManager</code>. These crop up regularly throughout the remainder of this document so it`s important you know how they are configured and how they operate.</p>
                </div>
                <div class="sect2">
                    <h3 id="core-services-authentication-manager"><a class="anchor" href="#core-services-authentication-manager"></a>2.1. AuthenticationManager, ProviderManager 以及 AuthenticationProvider</h3>
                    <div class="paragraph">
                        <p><code>AuthenticationManager</code> 仅仅是一个接口，所以它的实现可以是我们的任意选择，但是在实践中它是如何工作的？
                            假如我们需要检查多个认证数据库或者是一个不同认证的混合服务，比如，数据库和LDAP服务，那将会怎样？</p>
                    </div>
                    <div class="paragraph">
                        <p>The default implementation in Spring Security is called <code>ProviderManager</code> and rather than handling the authentication request itself, it delegates to a list of configured <code>AuthenticationProvider</code> s, each of which is queried in turn to see if it can perform the authentication. Each provider will either throw an exception or return a fully populated <code>Authentication</code> object. Remember our good friends, <code>UserDetails</code> and <code>UserDetailsService</code>? If not, head back to the previous chapter and refresh your memory. The most common approach to verifying an authentication request is to load the corresponding <code>UserDetails</code> and check the loaded password against the one that has been entered by the user. This is the approach used by the <code>DaoAuthenticationProvider</code> (see below). The loaded <code>UserDetails</code> object - and particularly the <code>GrantedAuthority</code> s it contains - will be used when building the fully populated <code>Authentication</code> object which is returned from a successful authentication and stored in the <code>SecurityContext</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>If you are using the namespace, an instance of <code>ProviderManager</code> is created and maintained internally, and you add providers to it by using the namespace authentication provider elements (see <a href="#ns-auth-manager">the namespace chapter</a>). In this case, you should not declare a <code>ProviderManager</code> bean in your application context. However, if you are not using the namespace then you would declare it like so:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="authenticationManager"
     class="org.springframework.security.authentication.ProviderManager"&gt;
  &lt;property name="providers"&gt;
    &lt;list&gt;
      &lt;ref local="daoAuthenticationProvider"/&gt;
      &lt;ref local="anonymousAuthenticationProvider"/&gt;
      &lt;ref local="ldapAuthenticationProvider"/&gt;
    &lt;/list&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>In the above example we have three providers. They are tried in the order shown (which is implied by the use of a <code>List</code>), with each provider able to attempt authentication, or skip authentication by simply returning <code>null</code>. If all implementations return null, the <code>ProviderManager</code> will throw a <code>ProviderNotFoundException</code>. If you`re interested in learning more about chaining providers, please refer to the <code>ProviderManager</code> JavaDocs.</p>
                    </div>
                    <div class="paragraph">
                        <p>Authentication mechanisms such as a web form-login processing filter are injected with a reference to the <code>ProviderManager</code> and will call it to handle their authentication requests. The providers you require will sometimes be interchangeable with the authentication mechanisms, while at other times they will depend on a specific authentication mechanism. For example, <code>DaoAuthenticationProvider</code> and <code>LdapAuthenticationProvider</code> are compatible with any mechanism which submits a simple username/password authentication request and so will work with form-based logins or HTTP Basic authentication. On the other hand, some authentication mechanisms create an authentication request object which can only be interpreted by a single type of <code>AuthenticationProvider</code>. An example of this would be JA-SIG CAS, which uses the notion of a service ticket and so can therefore only be authenticated by a <code>CasAuthenticationProvider</code>. You needn`t be too concerned about this, because if you forget to register a suitable provider, you`ll simply receive a <code>ProviderNotFoundException</code> when an attempt to authenticate is made.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="core-services-erasing-credentials"><a class="anchor" href="#core-services-erasing-credentials"></a>2.1.1. Erasing Credentials on Successful Authentication</h4>
                        <div class="paragraph">
                            <p>By default (from Spring Security 3.1 onwards) the <code>ProviderManager</code> will attempt to clear any sensitive credentials information from the <code>Authentication</code> object which is returned by a successful authentication request. This prevents information like passwords being retained longer than necessary.</p>
                        </div>
                        <div class="paragraph">
                            <p>This may cause issues when you are using a cache of user objects, for example, to improve performance in a stateless application. If the <code>Authentication</code> contains a reference to an object in the cache (such as a <code>UserDetails</code> instance) and this has its credentials removed, then it will no longer be possible to authenticate against the cached value. You need to take this into account if you are using a cache. An obvious solution is to make a copy of the object first, either in the cache implementation or in the <code>AuthenticationProvider</code> which creates the returned <code>Authentication</code> object. Alternatively, you can disable the <code>eraseCredentialsAfterAuthentication</code> property on <code>ProviderManager</code>. See the Javadoc for more information.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="core-services-dao-provider"><a class="anchor" href="#core-services-dao-provider"></a>2.1.2. DaoAuthenticationProvider</h4>
                        <div class="paragraph">
                            <p>The simplest <code>AuthenticationProvider</code> implemented by Spring Security is <code>DaoAuthenticationProvider</code>, which is also one of the earliest supported by the framework. It leverages a <code>UserDetailsService</code> (as a DAO) in order to lookup the username, password and <code>GrantedAuthority</code> s. It authenticates the user simply by comparing the password submitted in a <code>UsernamePasswordAuthenticationToken</code> against the one loaded by the <code>UserDetailsService</code>. Configuring the provider is quite simple:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="daoAuthenticationProvider"
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"&gt;
  &lt;property name="userDetailsService" ref="inMemoryDaoImpl"/&gt;
  &lt;property name="passwordEncoder" ref="passwordEncoder"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>PasswordEncoder</code> is optional. A <code>PasswordEncoder</code> provides encoding and decoding of passwords presented in the <code>UserDetails</code> object that is returned from the configured <code>UserDetailsService</code>. This will be discussed in more detail <a href="#core-services-password-encoding">below</a>.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="userdetailsservice-implementations"><a class="anchor" href="#userdetailsservice-implementations"></a>2.2. UserDetailsService的实现</h3>
                    <div class="paragraph">
                        <p>As mentioned in the earlier in this reference guide, most authentication providers take advantage of the <code>UserDetails</code> and <code>UserDetailsService</code> interfaces. Recall that the contract for <code>UserDetailsService</code> is a single method:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The returned <code>UserDetails</code> is an interface that provides getters that guarantee non-null provision of authentication information such as the username, password, granted authorities and whether the user account is enabled or disabled. Most authentication providers will use a`UserDetailsService`, even if the username and password are not actually used as part of the authentication decision. They may use the returned <code>UserDetails</code> object just for its <code>GrantedAuthority</code> information, because some other system (like LDAP or X.509 or CAS etc) has undertaken the responsibility of actually validating the credentials.</p>
                    </div>
                    <div class="paragraph">
                        <p>Given <code>UserDetailsService</code> is so simple to implement, it should be easy for users to retrieve authentication information using a persistence strategy of their choice. Having said that, Spring Security does include a couple of useful base implementations, which we`ll look at below.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="core-services-in-memory-service"><a class="anchor" href="#core-services-in-memory-service"></a>2.2.1. In-Memory Authentication</h4>
                        <div class="paragraph">
                            <p>Is easy to use create a custom <code>UserDetailsService</code> implementation that extracts information from a persistence engine of choice, but many applications do not require such complexity. This is particularly true if you`re building a prototype application or just starting integrating Spring Security, when you don`t really want to spend time configuring databases or writing <code>UserDetailsService</code> implementations. For this sort of situation, a simple option is to use the <code>user-service</code> element from the security <a href="#ns-minimal">namespace</a>:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;user-service id="userDetailsService"&gt;
  &lt;user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" /&gt;
  &lt;user name="bob" password="bobspassword" authorities="ROLE_USER" /&gt;
&lt;/user-service&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This also supports the use of an external properties file:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;user-service id="userDetailsService" properties="users.properties"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The properties file should contain entries in the form</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint txt language-txt"><code>username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>For example</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint txt language-txt"><code>jimi=jimispassword,ROLE_USER,ROLE_ADMIN,enabled
bob=bobspassword,ROLE_USER,enabled</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="core-services-jdbc-user-service"><a class="anchor" href="#core-services-jdbc-user-service"></a>2.2.2. JdbcDaoImpl</h4>
                        <div class="paragraph">
                            <p>Spring Security also includes a <code>UserDetailsService</code> that can obtain authentication information from a JDBC data source. Internally Spring JDBC is used, so it avoids the complexity of a fully-featured object relational mapper (ORM) just to store user details. If your application does use an ORM tool, you might prefer to write a custom <code>UserDetailsService</code> to reuse the mapping files you`ve probably already created. Returning to <code>JdbcDaoImpl</code>, an example configuration is shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
  &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver"/&gt;
  &lt;property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/&gt;
  &lt;property name="username" value="sa"/&gt;
  &lt;property name="password" value=""/&gt;
&lt;/bean&gt;

&lt;bean id="userDetailsService"
      class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"&gt;
  &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You can use different relational database management systems by modifying the <code>DriverManagerDataSource</code> shown above. You can also use a global data source obtained from JNDI, as with any other Spring configuration.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="authority-groups"><a class="anchor" href="#authority-groups"></a>Authority Groups</h5>
                            <div class="paragraph">
                                <p>By default, <code>JdbcDaoImpl</code> loads the authorities for a single user with the assumption that the authorities are mapped directly to users (see the <a href="#appendix-schema">database schema appendix</a>). An alternative approach is to partition the authorities into groups and assign groups to the user. Some people prefer this approach as a means of administering user rights. See the <code>JdbcDaoImpl</code> Javadoc for more information on how to enable the use of group authorities. The group schema is also included in the appendix.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="core-services-password-encoding"><a class="anchor" href="#core-services-password-encoding"></a>2.3. 密码编码</h3>
                    <div class="paragraph">
                        <p>Spring Security的 <code>PasswordEncoder</code> 接口是被用来支持使用永久存储的方式而需要编码密码的情况。你不应该明文存储密码。
                            始终使用一个单向密码散列算法如bcrypt，它为每个要存储的密码使用一个不同内置的盐值。
                            不要使用普通的哈希函数，如MD5或SHA，甚至是加盐版（a salted version）。
                            Bcrypt is deliberately designed to be slow and to hinder offline password cracking,
                            whereas standard hash algorithms are fast and can easily be used to test thousands of passwords in parallel on custom hardware.
                            You might think this doesn`t apply to you since your password database is secure and offline attacks aren`t a risk.
                            If so, do some research and read up on all the high-profile sites which have been compromised in this way and have been pilloried for storing their passwords insecurely. It`s best to be on the safe side. Using <code>org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"</code> is a good choice for security. There are also compatible implementations in other common programming languages so it a good choice for interoperability too.</p>
                    </div>
                    <div class="paragraph">
                        <p>If you are using a legacy system which already has hashed passwords, then you will need to use an encoder which matches your current algorithm, at least until you can migrate your users to a more secure scheme (usually this will involve asking the user to set a new password, since hashes are irreversible). Spring Security has a package containing legacy password encoding implementation, namely, <code>org.springframework.security.authentication.encoding</code>. The <code>DaoAuthenticationProvider</code> can be injected with either the new or legacy <code>PasswordEncoder</code> types.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="what-is-a-hash"><a class="anchor" href="#what-is-a-hash"></a>2.3.1. What is a hash?</h4>
                        <div class="paragraph">
                            <p>Password hashing is not unique to Spring Security but is a common source of confusion for users who are not familiar with the concept. A hash (or digest) algorithm is a one-way function which produces a piece of fixed-length output data (the hash) from some input data, such as a password. As an example, the MD5 hash of the string "password" (in hexadecimal) is</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint txt language-txt"><code>5f4dcc3b5aa765d61d8327deb882cf99</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>A hash is "one-way" in the sense that it is very difficult (effectively impossible) to obtain the original input given the hash value, or indeed any possible input which would produce that hash value. This property makes hash values very useful for authentication purposes. They can be stored in your user database as an alternative to plaintext passwords and even if the values are compromised they do not immediately reveal a password which can be used to login. Note that this also means you have no way of recovering the password once it is encoded.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="adding-salt-to-a-hash"><a class="anchor" href="#adding-salt-to-a-hash"></a>2.3.2. Adding Salt to a Hash</h4>
                        <div class="paragraph">
                            <p>One potential problem with the use of password hashes that it is relatively easy to get round the one-way property of the hash if a common word is used for the input. People tend to choose similar passwords and huge dictionaries of these from previously hacked sites are available online. For example, if you search for the hash value <code>5f4dcc3b5aa765d61d8327deb882cf99</code> using google, you will quickly find the original word "password". In a similar way, an attacker can build a dictionary of hashes from a standard word list and use this to lookup the original password. One way to help prevent this is to have a suitably strong password policy to try to prevent common words from being used. Another is to use a"salt" when calculating the hashes. This is an additional string of known data for each user which is combined with the password before calculating the hash. Ideally the data should be as random as possible, but in practice any salt value is usually preferable to none. Using a salt means that an attacker has to build a separate dictionary of hashes for each salt value, making the attack more complicated (but not impossible).</p>
                        </div>
                        <div class="paragraph">
                            <p>Bcrypt automatically generates a random salt value for each password when it is encoded, and stores it in the bcrypt string in a standard format.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>The legacy approach to handling salt was to inject a <code>SaltSource</code> into the <code>DaoAuthenticationProvider</code>, which would obtain a salt value for a particular user and pass it to the <code>PasswordEncoder</code>. Using bcrypt means you don`t have worry about the details of salt handling (such as where the the value is stored), as it is all done internally. So we`d strongly recommend you use bcrypt unless you already have a system in place which stores the salt separately.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="hashing-and-authentication"><a class="anchor" href="#hashing-and-authentication"></a>2.3.3. Hashing and Authentication</h4>
                        <div class="paragraph">
                            <p>When an authentication provider (such as Spring Security`s <code>DaoAuthenticationProvider</code>) needs to check the password in a submitted authentication request against the known value for a user, and the stored password is encoded in some way, then the submitted value must be encoded using exactly the same algorithm. It`s up to you to check that these are compatible as Spring Security has no control over the persistent values. If you add password hashing to your authentication configuration in Spring Security, and your database contains plaintext passwords, then there is no way authentication can succeed. Even if you are aware that your database is using MD5 to encode the passwords, for example, and your application is configured to use Spring Security`s <code>Md5PasswordEncoder</code>, there are still things that can go wrong. The database may have the passwords encoded in Base 64, for example while the encoder is using hexadecimal strings (the default). Alternatively your database may be using upper-case while the output from the encoder is lower-case. Make sure you write a test to check the output from your configured password encoder with a known password and salt combination and check that it matches the database value before going further and attempting to authenticate through your application. Using a standard like bcrypt will avoid these issues.</p>
                        </div>
                        <div class="paragraph">
                            <p>If you want to generate encoded passwords directly in Java for storage in your user database, then you can use the <code>encode</code> method on the <code>PasswordEncoder</code>.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <h1 id="web-app-security" class="sect0"><a class="anchor" href="#web-app-security"></a>Web应用程序安全</h1>
        <div class="paragraph">
            <p>大多数Spring Security的使用者，将会使用框架应用到有HTTP协议和Servlet API的应用程序中。
                在这一章节中，我来看看Spring Security如何为web层的应用程序提供认证和访问控制插件的。
                稍后我们会看到命名空间的正面，同时看看经过拼接后，实际为web层提供安全的类和接口。
                在某些情况下，使用传统bean配置来提供完全控制是必要的，所以我还将看到，在不使用命名空间直接使用这些类是如何配置的。</p>
        </div>
        <div class="sect1">
            <h2 id="security-filter-chain"><a class="anchor" href="#security-filter-chain"></a>1. Security过滤器链</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Spring Security`s web infrastructure is based entirely on standard servlet filters.
                        It doesn`t use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology.
                        It deals in <code>HttpServletRequest</code> s and <code>HttpServletResponse</code> s and doesn`t care whether the requests come from a browser, a web service client, an <code>HttpInvoker</code> or an AJAX application.</p>
                </div>
                <div class="paragraph">
                    <p>Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required. The ordering of the filters is important as there are dependencies between them. If you have been using <a href="#ns-config">namespace configuration</a>, then the filters are automatically configured for you and you don`t have to define any Spring beans explicitly but here may be times when you want full control over the security filter chain, either because you are using features which aren`t supported in the namespace, or you are using your own customized versions of classes.</p>
                </div>
                <div class="sect2">
                    <h3 id="delegating-filter-proxy"><a class="anchor" href="#delegating-filter-proxy"></a>1.1. DelegatingFilterProxy</h3>
                    <div class="paragraph">
                        <p>When using servlet filters, you obviously need to declare them in your <code>web.xml</code>, or they will be ignored by the servlet container. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring`s rich dependency-injection facilities and lifecycle interfaces. Spring`s <code>DelegatingFilterProxy</code> provides the link between <code>web.xml</code> and the application context.</p>
                    </div>
                    <div class="paragraph">
                        <p>When using <code>DelegatingFilterProxy</code>, you will see something like this in the <code>web.xml</code> file:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;filter&gt;
  &lt;filter-name&gt;myFilter&lt;/filter-name&gt;
  &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
  &lt;filter-name&gt;myFilter&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Notice that the filter is actually a <code>DelegatingFilterProxy</code>, and not the class that will actually implement the logic of the filter. What <code>DelegatingFilterProxy</code> does is delegate the <code>Filter</code>'s methods through to a bean which is obtained from the Spring application context. This enables the bean to benefit from the Spring web application context lifecycle support and configuration flexibility. The bean must implement <code>javax.servlet.Filter</code> and it must have the same name as that in the <code>filter-name</code> element. Read the Javadoc for <code>DelegatingFilterProxy</code> for more information</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="filter-chain-proxy"><a class="anchor" href="#filter-chain-proxy"></a>1.2. FilterChainProxy</h3>
                    <div class="paragraph">
                        <p>Spring Security`s web infrastructure should only be used by delegating to an instance of <code>FilterChainProxy</code>. The security filters should not be used by themselves. In theory you could declare each Spring Security filter bean that you require in your application context file and add a corresponding <code>DelegatingFilterProxy</code> entry to <code>web.xml</code> for each filter, making sure that they are ordered correctly, but this would be cumbersome and would clutter up the <code>web.xml</code> file quickly if you have a lot of filters. <code>FilterChainProxy</code> lets us add a single entry to <code>web.xml</code> and deal entirely with the application context file for managing our web security beans. It is wired using a <code>DelegatingFilterProxy</code>, just like in the example above, but with the <code>filter-name</code> set to the bean name "filterChainProxy". The filter chain is then declared in the application context with the same bean name. Here`s an example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy"&gt;
  &lt;constructor-arg&gt;
    &lt;list&gt;
      &lt;sec:filter-chain pattern="/restful/**" filters="
           securityContextPersistenceFilterWithASCFalse,
           basicAuthenticationFilter,
           exceptionTranslationFilter,
           filterSecurityInterceptor" /&gt;
      &lt;sec:filter-chain pattern="/**" filters="
           securityContextPersistenceFilterWithASCTrue,
           formLoginFilter,
           exceptionTranslationFilter,
           filterSecurityInterceptor" /&gt;
    &lt;/list&gt;
  &lt;/constructor-arg&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The namespace element <code>filter-chain</code> is used for convenience to set up the security filter chain(s) which are required within the application. <span class="footnote">[<a id="_footnoteref_8" class="footnote" href="#_footnote_8" title="View footnote.">8</a>]</span>. It maps a particular URL pattern to a list of filters built up from the bean names specified in the <code>filters</code> element, and combines them in a bean of type <code>SecurityFilterChain</code>. The <code>pattern</code> attribute takes an Ant Paths and the most specific URIs should appear first <span class="footnote">[<a id="_footnoteref_9" class="footnote" href="#_footnote_9" title="View footnote.">9</a>]</span>. At runtime the <code>FilterChainProxy</code> will locate the first URI pattern that matches the current web request and the list of filter beans specified by the <code>filters</code> attribute will be applied to that request. The filters will be invoked in the order they are defined, so you have complete control over the filter chain which is applied to a particular URL.</p>
                    </div>
                    <div class="paragraph">
                        <p>You may have noticed we have declared two <code>SecurityContextPersistenceFilter</code> s in the filter chain ( <code>ASC</code> is short for <code>allowSessionCreation</code>, a property of <code>SecurityContextPersistenceFilter</code>). As web services will never present a <code>jsessionid</code> on future requests, creating <code>HttpSession</code> s for such user agents would be wasteful. If you had a high-volume application which required maximum scalability, we recommend you use the approach shown above. For smaller applications, using a single <code>SecurityContextPersistenceFilter</code> (with its default <code>allowSessionCreation</code> as <code>true</code>) would likely be sufficient.</p>
                    </div>
                    <div class="paragraph">
                        <p>Note that <code>FilterChainProxy</code> does not invoke standard filter lifecycle methods on the filters it is configured with. We recommend you use Spring`s application context lifecycle interfaces as an alternative, just as you would for any other Spring bean.</p>
                    </div>
                    <div class="paragraph">
                        <p>When we looked at how to set up web security using <a href="#ns-web-xml">namespace configuration</a>, we used a <code>DelegatingFilterProxy</code> with the name "springSecurityFilterChain". You should now be able to see that this is the name of the <code>FilterChainProxy</code> which is created by the namespace.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="bypassing-the-filter-chain"><a class="anchor" href="#bypassing-the-filter-chain"></a>1.2.1. Bypassing the Filter Chain</h4>
                        <div class="paragraph">
                            <p>You can use the attribute <code>filters = "none"</code> as an alternative to supplying a filter bean list. This will omit the request pattern from the security filter chain entirely. Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible. If you want to make use of the contents of the <code>SecurityContext</code> contents during a request, then it must have passed through the security filter chain. Otherwise the <code>SecurityContextHolder</code> will not have been populated and the contents will be null.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="filter-ordering"><a class="anchor" href="#filter-ordering"></a>1.3. Filter Ordering</h3>
                    <div class="paragraph">
                        <p>The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p><code>ChannelProcessingFilter</code>, because it might need to redirect to a different protocol</p>
                            </li>
                            <li>
                                <p><code>SecurityContextPersistenceFilter</code>, so a <code>SecurityContext</code> can be set up in the <code>SecurityContextHolder</code> at the beginning of a web request, and any changes to the <code>SecurityContext</code> can be copied to the <code>HttpSession</code> when the web request ends (ready for use with the next web request)</p>
                            </li>
                            <li>
                                <p><code>ConcurrentSessionFilter</code>, because it uses the <code>SecurityContextHolder</code> functionality and needs to update the <code>SessionRegistry</code> to reflect ongoing requests from the principal</p>
                            </li>
                            <li>
                                <p>Authentication processing mechanisms - <code>UsernamePasswordAuthenticationFilter</code>, <code>CasAuthenticationFilter</code>, <code>BasicAuthenticationFilter</code> etc - so that the <code>SecurityContextHolder</code> can be modified to contain a valid <code>Authentication</code> request token</p>
                            </li>
                            <li>
                                <p>The <code>SecurityContextHolderAwareRequestFilter</code>, if you are using it to install a Spring Security aware <code>HttpServletRequestWrapper</code> into your servlet container</p>
                            </li>
                            <li>
                                <p>The <code>JaasApiIntegrationFilter</code>, if a <code>JaasAuthenticationToken</code> is in the <code>SecurityContextHolder</code> this will process the <code>FilterChain</code> as the <code>Subject</code> in the <code>JaasAuthenticationToken</code></p>
                            </li>
                            <li>
                                <p><code>RememberMeAuthenticationFilter</code>, so that if no earlier authentication processing mechanism updated the <code>SecurityContextHolder</code>, and the request presents a cookie that enables remember-me services to take place, a suitable remembered <code>Authentication</code> object will be put there</p>
                            </li>
                            <li>
                                <p><code>AnonymousAuthenticationFilter</code>, so that if no earlier authentication processing mechanism updated the <code>SecurityContextHolder</code>, an anonymous <code>Authentication</code> object will be put there</p>
                            </li>
                            <li>
                                <p><code>ExceptionTranslationFilter</code>, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate <code>AuthenticationEntryPoint</code> can be launched</p>
                            </li>
                            <li>
                                <p><code>FilterSecurityInterceptor</code>, to protect web URIs and raise exceptions when access is denied</p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="request-matching"><a class="anchor" href="#request-matching"></a>1.4. Request Matching and HttpFirewall</h3>
                    <div class="paragraph">
                        <p>Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled. This occurs when the <code>FilterChainProxy</code> decides which filter chain a request should be passed through and also when the <code>FilterSecurityInterceptor</code> decides which security constraints apply to a request. It`s important to understand what the mechanism is and what URL value is used when testing against the patterns that you define.</p>
                    </div>
                    <div class="paragraph">
                        <p>The Servlet Specification defines several properties for the <code>HttpServletRequest</code> which are accessible via getter methods, and which we might want to match against. These are the <code>contextPath</code>, <code>servletPath</code>, <code>pathInfo</code> and <code>queryString</code>. Spring Security is only interested in securing paths within the application, so the <code>contextPath</code> is ignored. Unfortunately, the servlet spec does not define exactly what the values of <code>servletPath</code> and <code>pathInfo</code> will contain for a particular request URI. For example, each path segment of a URL may contain parameters, as defined in <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a> <span class="footnote">[<a id="_footnoteref_10" class="footnote" href="#_footnote_10" title="View footnote.">10</a>]</span>. The Specification does not clearly state whether these should be included in the <code>servletPath</code> and <code>pathInfo</code> values and the behaviour varies between different servlet containers. There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly. <span class="footnote">[<a id="_footnoteref_11" class="footnote" href="#_footnote_11" title="View footnote.">11</a>]</span>. Other variations in the incoming URL are also possible. For example, it could contain path-traversal sequences (like <code>/../</code>) or multiple forward slashes (<code>//</code>) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don`t. To protect against issues like these, <code>FilterChainProxy</code> uses an <code>HttpFirewall</code> strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes. <span class="footnote">[<a id="_footnoteref_12" class="footnote" href="#_footnote_12" title="View footnote.">12</a>]</span>. It is therefore essential that a <code>FilterChainProxy</code> is used to manage the security filter chain. Note that the <code>servletPath</code> and <code>pathInfo</code> values are decoded by the container, so your application should not have any valid paths which contain semi-colons, as these parts will be removed for matching purposes.</p>
                    </div>
                    <div class="paragraph">
                        <p>As mentioned above, the default strategy is to use Ant-style paths for matching and this is likely to be the best choice for most users. The strategy is implemented in the class <code>AntPathRequestMatcher</code> which uses Spring`s <code>AntPathMatcher</code> to perform a case-insensitive match of the pattern against the concatenated <code>servletPath</code> and <code>pathInfo</code>, ignoring the <code>queryString</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>If for some reason, you need a more powerful matching strategy, you can use regular expressions. The strategy implementation is then`RegexRequestMatcher`. See the Javadoc for this class for more information.</p>
                    </div>
                    <div class="paragraph">
                        <p>In practice we recommend that you use method security at your service layer, to control access to your application, and do not rely entirely on the use of security constraints defined at the web-application level. URLs change and it is difficult to take account of all the possible URLs that an application might support and how requests might be manipulated. You should try and restrict yourself to using a few simple ant paths which are simple to understand. Always try to use a"deny-by-default" approach where you have a catch-all wildcard ( <code>/**</code> or <code>**</code>) defined last and denying access.</p>
                    </div>
                    <div class="paragraph">
                        <p>Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security`s method security options.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="use-with-other-filter-based-frameworks"><a class="anchor" href="#use-with-other-filter-based-frameworks"></a>1.5. Use with other Filter-Based Frameworks</h3>
                    <div class="paragraph">
                        <p>If you`re using some other framework that is also filter-based, then you need to make sure that the Spring Security filters come first. This enables the <code>SecurityContextHolder</code> to be populated in time for use by the other filters. Examples are the use of SiteMesh to decorate your web pages or a web framework like Wicket which uses a filter to handle its requests.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="filter-chains-with-ns"><a class="anchor" href="#filter-chains-with-ns"></a>1.6. Advanced Namespace Configuration</h3>
                    <div class="paragraph">
                        <p>As we saw earlier in the namespace chapter, it`s possible to use multiple <code>http</code> elements to define different security configurations for different URL patterns. Each element creates a filter chain within the internal <code>FilterChainProxy</code> and the URL pattern that should be mapped to it. The elements will be added in the order they are declared, so the most specific patterns must again be declared first. Here`s another example, for a similar situation to that above, where the application supports both a stateless RESTful API and also a normal web application which users log into using a form.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;!-- Stateless RESTful service using Basic authentication --&gt;
&lt;http pattern="/restful/**" create-session="stateless"&gt;
  &lt;intercept-url pattern='/**' access='ROLE_REMOTE' /&gt;
  &lt;http-basic /&gt;
&lt;/http&gt;

&lt;!-- Empty filter chain for the login page --&gt;
&lt;http pattern="/login.htm*" security="none"/&gt;

&lt;!-- Additional filter chain for normal users, matching all other requests --&gt;
&lt;http&gt;
  &lt;intercept-url pattern='/**' access='ROLE_USER' /&gt;
  &lt;form-login login-page='/login.htm' default-target-url="/home.htm"/&gt;
  &lt;logout /&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="core-web-filters"><a class="anchor" href="#core-web-filters"></a>2. Core Security Filters</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>There are some key filters which will always be used in a web application which uses Spring Security, so we`ll look at these and their supporting classes and interfaces first. We won`t cover every feature, so be sure to look at the Javadoc for them if you want to get the complete picture.</p>
                </div>
                <div class="sect2">
                    <h3 id="filter-security-interceptor"><a class="anchor" href="#filter-security-interceptor"></a>2.1. FilterSecurityInterceptor</h3>
                    <div class="paragraph">
                        <p>We`ve already seen <code>FilterSecurityInterceptor</code> briefly when discussing <a href="#tech-intro-access-control">access-control in general</a>, and we`ve already used it with the namespace where the <code>&lt;intercept-url&gt;</code> elements are combined to configure it internally. Now we`ll see how to explicitly configure it for use with a`FilterChainProxy`, along with its companion filter <code>ExceptionTranslationFilter</code>. A typical configuration example is shown below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="filterSecurityInterceptor"
      class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="accessDecisionManager" ref="accessDecisionManager"/&gt;
  &lt;property name="securityMetadataSource"&gt;
    &lt;security:filter-security-metadata-source&gt;
      &lt;security:intercept-url pattern="/secure/super/**" access="ROLE_WE_DONT_HAVE"/&gt;
      &lt;security:intercept-url pattern="/secure/**" access="ROLE_SUPERVISOR,ROLE_TELLER"/&gt;
    &lt;/security:filter-security-metadata-source&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p><code>FilterSecurityInterceptor</code> is responsible for handling the security of HTTP resources. It requires a reference to an <code>AuthenticationManager</code> and an <code>AccessDecisionManager</code>. It is also supplied with configuration attributes that apply to different HTTP URL requests. Refer back to <a href="#tech-intro-config-attributes">the original discussion on these</a> in the technical introduction.</p>
                    </div>
                    <div class="paragraph">
                        <p>The <code>FilterSecurityInterceptor</code> can be configured with configuration attributes in two ways. The first, which is shown above, is using the <code>&lt;filter-security-metadata-source&gt;</code> namespace element. This is similar to the <code>&lt;http&gt;</code> element from the namespace chapter but the <code>&lt;intercept-url&gt;</code> child elements only use the <code>pattern</code> and <code>access</code> attributes. Commas are used to delimit the different configuration attributes that apply to each HTTP URL. The second option is to write your own`SecurityMetadataSource`, but this is beyond the scope of this document. Irrespective of the approach used, the <code>SecurityMetadataSource</code> is responsible for returning a <code>List&lt;ConfigAttribute&gt;</code> containing all of the configuration attributes associated with a single secure HTTP URL.</p>
                    </div>
                    <div class="paragraph">
                        <p>It should be noted that the <code>FilterSecurityInterceptor.setSecurityMetadataSource()</code> method actually expects an instance of <code>FilterInvocationSecurityMetadataSource</code>. This is a marker interface which subclasses`SecurityMetadataSource`. It simply denotes the <code>SecurityMetadataSource</code> understands <code>FilterInvocation</code> s. In the interests of simplicity we`ll continue to refer to the <code>FilterInvocationSecurityMetadataSource</code> as a <code>SecurityMetadataSource</code>, as the distinction is of little relevance to most users.</p>
                    </div>
                    <div class="paragraph">
                        <p>The <code>SecurityMetadataSource</code> created by the namespace syntax obtains the configuration attributes for a particular <code>FilterInvocation</code> by matching the request URL against the configured <code>pattern</code> attributes. This behaves in the same way as it does for namespace configuration. The default is to treat all expressions as Apache Ant paths and regular expressions are also supported for more complex cases. The <code>path-type</code> attribute is used to specify the type of pattern being used. It is not possible to mix expression syntaxes within the same definition. As an example, the previous configuration using regular expressions instead of Ant paths would be written as follows:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="filterInvocationInterceptor"
      class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="accessDecisionManager" ref="accessDecisionManager"/&gt;
  &lt;property name="runAsManager" ref="runAsManager"/&gt;
  &lt;property name="securityMetadataSource"&gt;
    &lt;security:filter-security-metadata-source path-type="regex"&gt;
      &lt;security:intercept-url pattern="\A/secure/super/.*\Z" access="ROLE_WE_DONT_HAVE"/&gt;
      &lt;security:intercept-url pattern="\A/secure/.*\" access="ROLE_SUPERVISOR,ROLE_TELLER"/&gt;
    &lt;/security:filter-security-metadata-source&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Patterns are always evaluated in the order they are defined. Thus it is important that more specific patterns are defined higher in the list than less specific patterns. This is reflected in our example above, where the more specific <code>/secure/super/</code> pattern appears higher than the less specific <code>/secure/</code> pattern. If they were reversed, the <code>/secure/</code> pattern would always match and the <code>/secure/super/</code> pattern would never be evaluated.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="exception-translation-filter"><a class="anchor" href="#exception-translation-filter"></a>2.2. ExceptionTranslationFilter</h3>
                    <div class="paragraph">
                        <p>The <code>ExceptionTranslationFilter</code> sits above the <code>FilterSecurityInterceptor</code> in the security filter stack. It doesn`t do any actual security enforcement itself, but handles exceptions thrown by the security interceptors and provides suitable and HTTP responses.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="exceptionTranslationFilter"
  class="org.springframework.security.web.access.ExceptionTranslationFilter"&gt;
 &lt;property name="authenticationEntryPoint" ref="authenticationEntryPoint"/&gt;
 &lt;property name="accessDeniedHandler" ref="accessDeniedHandler"/&gt;
&lt;/bean&gt;

&lt;bean id="authenticationEntryPoint"
  class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"&gt;
 &lt;property name="loginFormUrl" value="/login.jsp"/&gt;
&lt;/bean&gt;

&lt;bean id="accessDeniedHandler"
     class="org.springframework.security.web.access.AccessDeniedHandlerImpl"&gt;
  &lt;property name="errorPage" value="/accessDenied.htm"/&gt;
&lt;/bean&gt;
</code></pre>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="auth-entry-point"><a class="anchor" href="#auth-entry-point"></a>2.2.1. AuthenticationEntryPoint</h4>
                        <div class="paragraph">
                            <p>The <code>AuthenticationEntryPoint</code> will be called if the user requests a secure HTTP resource but they are not authenticated. An appropriate <code>AuthenticationException</code> or <code>AccessDeniedException</code> will be thrown by a security interceptor further down the call stack, triggering the <code>commence</code> method on the entry point. This does the job of presenting the appropriate response to the user so that authentication can begin. The one we`ve used here is <code>LoginUrlAuthenticationEntryPoint</code>, which redirects the request to a different URL (typically a login page). The actual implementation used will depend on the authentication mechanism you want to be used in your application.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="access-denied-handler"><a class="anchor" href="#access-denied-handler"></a>2.2.2. AccessDeniedHandler</h4>
                        <div class="paragraph">
                            <p>What happens if a user is already authenticated and they try to access a protected resource? In normal usage, this shouldn`t happen because the application workflow should be restricted to operations to which a user has access. For example, an HTML link to an administration page might be hidden from users who do not have an admin role. You can`t rely on hiding links for security though, as there`s always a possibility that a user will just enter the URL directly in an attempt to bypass the restrictions. Or they might modify a RESTful URL to change some of the argument values. Your application must be protected against these scenarios or it will definitely be insecure. You will typically use simple web layer security to apply constraints to basic URLs and use more specific method-based security on your service layer interfaces to really nail down what is permissible.</p>
                        </div>
                        <div class="paragraph">
                            <p>If an <code>AccessDeniedException</code> is thrown and a user has already been authenticated, then this means that an operation has been attempted for which they don`t have enough permissions. In this case, <code>ExceptionTranslationFilter</code> will invoke a second strategy, the <code>AccessDeniedHandler</code>. By default, an <code>AccessDeniedHandlerImpl</code> is used, which just sends a 403 (Forbidden) response to the client. Alternatively you can configure an instance explicitly (as in the above example) and set an error page URL which it will forwards the request to <span class="footnote">[<a id="_footnoteref_13" class="footnote" href="#_footnote_13" title="View footnote.">13</a>]</span>. This can be a simple "access denied" page, such as a JSP, or it could be a more complex handler such as an MVC controller. And of course, you can implement the interface yourself and use your own implementation.</p>
                        </div>
                        <div class="paragraph">
                            <p>It`s also possible to supply a custom <code>AccessDeniedHandler</code> when you`re using the namespace to configure your application. See <a href="#nsa-access-denied-handler">the namespace appendix</a> for more details.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="request-caching"><a class="anchor" href="#request-caching"></a>2.2.3. SavedRequest s and the RequestCache Interface</h4>
                        <div class="paragraph">
                            <p>Another of <code>ExceptionTranslationFilter</code>'s responsibilities is to save the current request before invoking the <code>AuthenticationEntryPoint</code>. This allows the request to be restored after the use has authenticated (see previous overview of <a href="#tech-intro-web-authentication">web authentication</a>). A typical example would be where the user logs in with a form, and is then redirected to the original URL by the default <code>SavedRequestAwareAuthenticationSuccessHandler</code> (see <a href="#form-login-flow-handling">below</a>).</p>
                        </div>
                        <div class="paragraph">
                            <p>The <code>RequestCache</code> encapsulates the functionality required for storing and retrieving <code>HttpServletRequest</code> instances. By default the <code>HttpSessionRequestCache</code> is used, which stores the request in the <code>HttpSession</code>. The <code>RequestCacheFilter</code> has the job of actually restoring the saved request from the cache when the user is redirected to the original URL.</p>
                        </div>
                        <div class="paragraph">
                            <p>Under normal circumstances, you shouldn`t need to modify any of this functionality, but the saved-request handling is a "best-effort" approach and there may be situations which the default configuration isn`t able to handle. The use of these interfaces makes it fully pluggable from Spring Security 3.0 onwards.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="security-context-persistence-filter"><a class="anchor" href="#security-context-persistence-filter"></a>2.3. SecurityContextPersistenceFilter</h3>
                    <div class="paragraph">
                        <p>We covered the purpose of this all-important filter in the <a href="#tech-intro-sec-context-persistence">Technical Overview</a> chapter so you might want to re-read that section at this point. Let`s first take a look at how you would configure it for use with a <code>FilterChainProxy</code>. A basic configuration only requires the bean itself</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="securityContextPersistenceFilter"
  class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>As we saw previously, this filter has two main tasks. It is responsible for storage of the <code>SecurityContext</code> contents between HTTP requests and for clearing the <code>SecurityContextHolder</code> when a request is completed. Clearing the <code>ThreadLocal</code> in which the context is stored is essential, as it might otherwise be possible for a thread to be replaced into the servlet container`s thread pool, with the security context for a particular user still attached. This thread might then be used at a later stage, performing operations with the wrong credentials.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="security-context-repository"><a class="anchor" href="#security-context-repository"></a>2.3.1. SecurityContextRepository</h4>
                        <div class="paragraph">
                            <p>From Spring Security 3.0, the job of loading and storing the security context is now delegated to a separate strategy interface:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface SecurityContextRepository {

  SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);

  void saveContext(SecurityContext context, HttpServletRequest request,
         HttpServletResponse response);
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>HttpRequestResponseHolder</code> is simply a container for the incoming request and response objects, allowing the implementation to replace these with wrapper classes. The returned contents will be passed to the filter chain.</p>
                        </div>
                        <div class="paragraph">
                            <p>The default implementation is <code>HttpSessionSecurityContextRepository</code>, which stores the security context as an <code>HttpSession</code> attribute <span class="footnote">[<a id="_footnoteref_14" class="footnote" href="#_footnote_14" title="View footnote.">14</a>]</span>. The most important configuration parameter for this implementation is the <code>allowSessionCreation</code> property, which defaults to <code>true</code>, thus allowing the class to create a session if it needs one to store the security context for an authenticated user (it won`t create one unless authentication has taken place and the contents of the security context have changed). If you don`t want a session to be created, then you can set this property to <code>false</code>:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="securityContextPersistenceFilter"
    class="org.springframework.security.web.context.SecurityContextPersistenceFilter"&gt;
  &lt;property name='securityContextRepository'&gt;
    &lt;bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'&gt;
      &lt;property name='allowSessionCreation' value='false' /&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Alternatively you could provide an instance of <code>NullSecurityContextRepository</code>, a "http://en.wikipedia.org/wiki/Null_Object_pattern[null object]" implementation, which will prevent the security context from being stored, even if a session has already been created during the request.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="form-login-filter"><a class="anchor" href="#form-login-filter"></a>2.4. UsernamePasswordAuthenticationFilter</h3>
                    <div class="paragraph">
                        <p>We`ve now seen the three main filters which are always present in a Spring Security web configuration. These are also the three which are automatically created by the namespace <code>&lt;http&gt;</code> element and cannot be substituted with alternatives. The only thing that`s missing now is an actual authentication mechanism, something that will allow a user to authenticate. This filter is the most commonly used authentication filter and the one that is most often customized <span class="footnote">[<a id="_footnoteref_15" class="footnote" href="#_footnote_15" title="View footnote.">15</a>]</span>. It also provides the implementation used by the <code>&lt;form-login&gt;</code> element from the namespace. There are three stages required to configure it.</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>Configure a <code>LoginUrlAuthenticationEntryPoint</code> with the URL of the login page, just as we did above, and set it on the <code>ExceptionTranslationFilter</code>.</p>
                            </li>
                            <li>
                                <p>Implement the login page (using a JSP or MVC controller).</p>
                            </li>
                            <li>
                                <p>Configure an instance of <code>UsernamePasswordAuthenticationFilter</code> in the application context</p>
                            </li>
                            <li>
                                <p>Add the filter bean to your filter chain proxy (making sure you pay attention to the order).</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>The login form simply contains <code>j_username</code> and <code>j_password</code> input fields, and posts to the URL that is monitored by the filter (by default this is <code>/j_spring_security_check</code>). The basic filter configuration looks something like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;bean id="authenticationFilter" class=
"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="form-login-flow-handling"><a class="anchor" href="#form-login-flow-handling"></a>2.4.1. Application Flow on Authentication Success and Failure</h4>
                        <div class="paragraph">
                            <p>The filter calls the configured <code>AuthenticationManager</code> to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the <code>AuthenticationSuccessHandler</code> and <code>AuthenticationFailureHandler</code> strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely <span class="footnote">[<a id="_footnoteref_16" class="footnote" href="#_footnote_16" title="View footnote.">16</a>]</span>. Some standard implementations are supplied such as <code>SimpleUrlAuthenticationSuccessHandler</code>, <code>SavedRequestAwareAuthenticationSuccessHandler</code>, <code>SimpleUrlAuthenticationFailureHandler</code> and <code>ExceptionMappingAuthenticationFailureHandler</code>. Have a look at the Javadoc for these classes and also for <code>AbstractAuthenticationProcessingFilter</code> to get an overview of how they work and the supported features.</p>
                        </div>
                        <div class="paragraph">
                            <p>If authentication is successful, the resulting <code>Authentication</code> object will be placed into the <code>SecurityContextHolder</code>. The configured <code>AuthenticationSuccessHandler</code> will then be called to either redirect or forward the user to the appropriate destination. By default a <code>SavedRequestAwareAuthenticationSuccessHandler</code> is used, which means that the user will be redirected to the original destination they requested before they were asked to login.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>The <code>ExceptionTranslationFilter</code> caches the original request a user makes. When the user authenticates, the request handler makes use of this cached request to obtain the original URL and redirect to it. The original request is then rebuilt and used as an alternative.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>If authentication fails, the configured <code>AuthenticationFailureHandler</code> will be invoked.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="servletapi"><a class="anchor" href="#servletapi"></a>3. Servlet API integration</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>This section describes how Spring Security is integrated with the Servlet API. The <a href="https://github.com/SpringSource/spring-security/blob/master/samples/servletapi-xml">servletapi-xml</a> sample application demonstrates the usage of each of these methods.</p>
                </div>
                <div class="sect2">
                    <h3 id="servletapi-25"><a class="anchor" href="#servletapi-25"></a>3.1. Servlet 2.5+ Integration</h3>
                    <div class="sect3">
                        <h4 id="servletapi-remote-user"><a class="anchor" href="#servletapi-remote-user"></a>3.1.1. HttpServletRequest.getRemoteUser()</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()">HttpServletRequest.getRemoteUser()</a> will return the result of <code>SecurityContextHolder.getContext().getAuthentication().getName()</code> which is typically the current username. This can be useful if you want to display the current username in your application. Additionally, checking if this is null can be used to indicate if a user has authenticated or is anonymous. Knowing if the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (i.e. a log out link should only be displayed if the user is authenticated).</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-user-principal"><a class="anchor" href="#servletapi-user-principal"></a>3.1.2. HttpServletRequest.getUserPrincipal()</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()">HttpServletRequest.getUserPrincipal()</a> will return the result of <code>SecurityContextHolder.getContext().getAuthentication()</code>. This means it is an <code>Authentication</code> which is typically an instance of <code>UsernamePasswordAuthenticationToken</code> when using username and password based authentication. This can be useful if you need additional information about your user. For example, you might have created a custom <code>UserDetailsService</code> that returns a custom <code>UserDetails</code> containing a first and last name for your user. You could obtain this information with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>Authentication auth = httpServletRequest.getUserPrincipal();
// assume integrated custom UserDetails called MyCustomUserDetails
// by default, typically instance of UserDetails
MyCustomUserDetails userDetails = (MyCustomUserDetails) auth.getPrincipal();
String firstName = userDetails.getFirstName();
String lastName = userDetails.getLastName();</code></pre>
                            </div>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>It should be noted that it is typically bad practice to perform so much logic throughout your application. Instead, one should centralize it to reduce any coupling of Spring Security and the Servlet API`s.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-user-in-role"><a class="anchor" href="#servletapi-user-in-role"></a>3.1.3. HttpServletRequest.isUserInRole(String)</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)">HttpServletRequest.isUserInRole(String)</a> will determine if <code>SecurityContextHolder.getContext().getAuthentication().getAuthorities()</code> contains a <code>GrantedAuthority</code> with the role passed into <code>isUserInRole(String)</code>. Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This might be useful to determine if certain UI components should be displayed. For example, you might display admin links only if the current user is an admin.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="servletapi-3"><a class="anchor" href="#servletapi-3"></a>3.2. Servlet 3+ Integration</h3>
                    <div class="paragraph">
                        <p>The following section describes the Servlet 3 methods that Spring Security integrates with.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-authenticate"><a class="anchor" href="#servletapi-authenticate"></a>3.2.1. HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29">HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)</a> method can be used to ensure that a user is authenticated. If they are not authenticated, the configured AuthenticationEntryPoint will be used to request the user to authenticate (i.e. redirect to the login page).</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-login"><a class="anchor" href="#servletapi-login"></a>3.2.2. HttpServletRequest.login(String,String)</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29">HttpServletRequest.login(String,String)</a> method can be used to authenticate the user with the current <code>AuthenticationManager</code>. For example, the following would attempt to authenticate with the username "user" and password "password":</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>try {
  httpServletRequest.login("user","password");
} catch(ServletException e) {
  // fail to authenticate
}</code></pre>
                            </div>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>It is not necessary to catch the ServletException if you want Spring Security to process the failed authentication attempt.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-logout"><a class="anchor" href="#servletapi-logout"></a>3.2.3. HttpServletRequest.logout()</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29">HttpServletRequest.logout()</a> method can be used to log the current user out.</p>
                        </div>
                        <div class="paragraph">
                            <p>Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any "Remember Me" authentication will be cleaned up, etc. However, the configured LogoutHandler implementations will vary depending on your Spring Security configuration. It is important to note that after HttpServletRequest.logout() has been invoked, you are still in charge of writing a response out. Typically this would involve a redirect to the welcome page.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-start-runnable"><a class="anchor" href="#servletapi-start-runnable"></a>3.2.4. AsyncContext.start(Runnable)</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29">AsynchContext.start(Runnable)</a> method that ensures your credentials will be propagated to the new Thread. Using Spring Security`s concurrency support, Spring Security overrides the AsyncContext.start(Runnable) to ensure that the current SecurityContext is used when processing the Runnable. For example, the following would output the current user`s Authentication:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>final AsyncContext async = httpServletRequest.startAsync();
async.start(new Runnable() {
    public void run() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        try {
            final HttpServletResponse asyncResponse = (HttpServletResponse) async.getResponse();
            asyncResponse.setStatus(HttpServletResponse.SC_OK);
            asyncResponse.getWriter().write(String.valueOf(authentication));
            async.complete();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
});</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-async"><a class="anchor" href="#servletapi-async"></a>3.2.5. Async Servlet Support</h4>
                        <div class="paragraph">
                            <p>If you are using Java Based configuration, you are ready to go. If you are using XML configuration, there are a few updates that are necessary. The first step is to ensure you have updated your web.xml to use at least the 3.0 schema as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"&gt;

&lt;/web-app&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Next you need to ensure that your springSecurityFilterChain is setup for processing asynchronous requests.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;filter&gt;
  &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
  &lt;filter-class&gt;
    org.springframework.web.filter.DelegatingFilterProxy
  &lt;/filter-class&gt;
  &lt;async-supported&gt;true&lt;/async-supported&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
  &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
  &lt;dispatcher&gt;ASYNC&lt;/dispatcher&gt;
&lt;/filter-mapping&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>That`s it! Now Spring Security will ensure that your SecurityContext is propagated on asynchronous requests too.</p>
                        </div>
                        <div class="paragraph">
                            <p>So how does it work? If you are not really interested, feel free to skip the remainder of this section, otherwise read on. Most of this is built into the Servlet specification, but there is a little bit of tweaking that Spring Security does to ensure things work with asynchronous requests properly. Prior to Spring Security 3.2, the SecurityContext from the SecurityContextHolder was automatically saved as soon as the HttpServletResponse was committed. This can cause issues in a Async environment. For example, consider the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>httpServletRequest.startAsync();
new Thread("AsyncThread") {
    @Override
    public void run() {
        try {
            // Do work
            TimeUnit.SECONDS.sleep(1);

            // Write to and commit the httpServletResponse
            httpServletResponse.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}.start();</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The issue is that this Thread is not known to Spring Security, so the SecurityContext is not propagated to it. This means when we commit the HttpServletResponse there is no SecuriytContext. When Spring Security automatically saved the SecurityContext on committing the HttpServletResponse it would lose our logged in user.</p>
                        </div>
                        <div class="paragraph">
                            <p>Since version 3.2, Spring Security is smart enough to no longer automatically save the SecurityContext on commiting the HttpServletResponse as soon as HttpServletRequest.startAsync() is invoked.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="servletapi-31"><a class="anchor" href="#servletapi-31"></a>3.3. Servlet 3.1+ Integration</h3>
                    <div class="paragraph">
                        <p>The following section describes the Servlet 3.1 methods that Spring Security integrates with.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="servletapi-change-session-id"><a class="anchor" href="#servletapi-change-session-id"></a>3.3.1. HttpServletRequest#changeSessionId()</h4>
                        <div class="paragraph">
                            <p>The <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId()">HttpServletRequest.changeSessionId()</a> is the default method for protecting against <a href="#ns-session-fixation">Session Fixation</a> attacks in Servlet 3.1 and higher.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="basic"><a class="anchor" href="#basic"></a>4. Basic and Digest Authentication</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Basic and digest authentiation are alternative authentication mechanisms which are popular in web applications. Basic authentication is often used with stateless clients which pass their credentials on each request. It`s quite common to use it in combination with form-based authentication where an application is used through both a browser-based user interface and as a web-service. However, basic authentication transmits the password as plain text so it should only really be used over an encrypted transport layer such as HTTPS.</p>
                </div>
                <div class="sect2">
                    <h3 id="basic-processing-filter"><a class="anchor" href="#basic-processing-filter"></a>4.1. BasicAuthenticationFilter</h3>
                    <div class="paragraph">
                        <p><code>BasicAuthenticationFilter</code> is responsible for processing basic authentication credentials presented in HTTP headers. This can be used for authenticating calls made by Spring remoting protocols (such as Hessian and Burlap), as well as normal browser user agents (such as Firefox and Internet Explorer). The standard governing HTTP Basic Authentication is defined by RFC 1945, Section 11, and <code>BasicAuthenticationFilter</code> conforms with this RFC. Basic Authentication is an attractive approach to authentication, because it is very widely deployed in user agents and implementation is extremely simple (it`s just a Base64 encoding of the username:password, specified in an HTTP header).</p>
                    </div>
                    <div class="sect3">
                        <h4 id="basic-config"><a class="anchor" href="#basic-config"></a>4.1.1. Configuration</h4>
                        <div class="paragraph">
                            <p>To implement HTTP Basic Authentication, you need to add a <code>BasicAuthenticationFilter</code> to your filter chain. The application context should contain <code>BasicAuthenticationFilter</code> and its required collaborator:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="basicAuthenticationFilter"
  class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="authenticationEntryPoint" ref="authenticationEntryPoint"/&gt;
&lt;/bean&gt;

&lt;bean id="authenticationEntryPoint"
  class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint"&gt;
  &lt;property name="realmName" value="Name Of Your Realm"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The configured <code>AuthenticationManager</code> processes each authentication request. If authentication fails, the configured <code>AuthenticationEntryPoint</code> will be used to retry the authentication process. Usually you will use the filter in combination with a`BasicAuthenticationEntryPoint`, which returns a 401 response with a suitable header to retry HTTP Basic authentication. If authentication is successful, the resulting <code>Authentication</code> object will be placed into the <code>SecurityContextHolder</code> as usual.</p>
                        </div>
                        <div class="paragraph">
                            <p>If the authentication event was successful, or authentication was not attempted because the HTTP header did not contain a supported authentication request, the filter chain will continue as normal. The only time the filter chain will be interrupted is if authentication fails and the <code>AuthenticationEntryPoint</code> is called.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="digest-processing-filter"><a class="anchor" href="#digest-processing-filter"></a>4.2. DigestAuthenticationFilter</h3>
                    <div class="paragraph">
                        <p><code>DigestAuthenticationFilter</code> is capable of processing digest authentication credentials presented in HTTP headers. Digest Authentication attempts to solve many of the weaknesses of Basic authentication, specifically by ensuring credentials are never sent in clear text across the wire. Many user agents support Digest Authentication, including FireFox and Internet Explorer. The standard governing HTTP Digest Authentication is defined by RFC 2617, which updates an earlier version of the Digest Authentication standard prescribed by RFC 2069. Most user agents implement RFC 2617. Spring Security`s <code>DigestAuthenticationFilter</code> is compatible with the "<code>auth</code>" quality of protection (<code>qop</code>) prescribed by RFC 2617, which also provides backward compatibility with RFC 2069. Digest Authentication is a more attractive option if you need to use unencrypted HTTP (i.e. no TLS/HTTPS) and wish to maximise security of the authentication process. Indeed Digest Authentication is a mandatory requirement for the WebDAV protocol, as noted by RFC 2518 Section 17.1.</p>
                    </div>
                    <div class="paragraph">
                        <p>Digest Authentication is definitely the most secure choice between Form Authentication, Basic Authentication and Digest Authentication, although extra security also means more complex user agent implementations. Central to Digest Authentication is a "nonce". This is a value the server generates. Spring Security`s nonce adopts the following format:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint txt language-txt"><code>base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
expirationTime:   The date and time when the nonce expires, expressed in milliseconds
key:              A private key to prevent modification of the nonce token</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The <code>DigestAuthenticatonEntryPoint</code> has a property specifying the <code>key</code> used for generating the nonce tokens, along with a <code>nonceValiditySeconds</code> property for determining the expiration time (default 300, which equals five minutes). Whist ever the nonce is valid, the digest is computed by concatenating various strings including the username, password, nonce, URI being requested, a client-generated nonce (merely a random value which the user agent generates each request), the realm name etc, then performing an MD5 hash. Both the server and user agent perform this digest computation, resulting in different hash codes if they disagree on an included value (eg password). In Spring Security implementation, if the server-generated nonce has merely expired (but the digest was otherwise valid), the <code>DigestAuthenticationEntryPoint</code> will send a <code>"stale=true"</code> header. This tells the user agent there is no need to disturb the user (as the password and username etc is correct), but simply to try again using a new nonce.</p>
                    </div>
                    <div class="paragraph">
                        <p>An appropriate value for <code>DigestAuthenticationEntryPoint</code>'s <code>nonceValiditySeconds</code> parameter will depend on your application. Extremely secure applications should note that an intercepted authentication header can be used to impersonate the principal until the <code>expirationTime</code> contained in the nonce is reached. This is the key principle when selecting an appropriate setting, but it would be unusual for immensely secure applications to not be running over TLS/HTTPS in the first instance.</p>
                    </div>
                    <div class="paragraph">
                        <p>Because of the more complex implementation of Digest Authentication, there are often user agent issues. For example, Internet Explorer fails to present an "<code>opaque</code>" token on subsequent requests in the same session. Spring Security filters therefore encapsulate all state information into the "<code>nonce</code>" token instead. In our testing, Spring Security`s implementation works reliably with FireFox and Internet Explorer, correctly handling nonce timeouts etc.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="digest-config"><a class="anchor" href="#digest-config"></a>4.2.1. Configuration</h4>
                        <div class="paragraph">
                            <p>Now that we`ve reviewed the theory, let`s see how to use it. To implement HTTP Digest Authentication, it is necessary to define <code>DigestAuthenticationFilter</code> in the filter chain. The application context will need to define the <code>DigestAuthenticationFilter</code> and its required collaborators:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="digestFilter" class=
    "org.springframework.security.web.authentication.www.DigestAuthenticationFilter"&gt;
  &lt;property name="userDetailsService" ref="jdbcDaoImpl"/&gt;
  &lt;property name="authenticationEntryPoint" ref="digestEntryPoint"/&gt;
  &lt;property name="userCache" ref="userCache"/&gt;
&lt;/bean&gt;

&lt;bean id="digestEntryPoint" class=
    "org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"&gt;
  &lt;property name="realmName" value="Contacts Realm via Digest Authentication"/&gt;
  &lt;property name="key" value="acegi"/&gt;
  &lt;property name="nonceValiditySeconds" value="10"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The configured <code>UserDetailsService</code> is needed because <code>DigestAuthenticationFilter</code> must have direct access to the clear text password of a user. Digest Authentication will NOT work if you are using encoded passwords in your DAO <span class="footnote">[<a id="_footnoteref_17" class="footnote" href="#_footnote_17" title="View footnote.">17</a>]</span>. The DAO collaborator, along with the <code>UserCache</code>, are typically shared directly with a <code>DaoAuthenticationProvider</code>. The <code>authenticationEntryPoint</code> property must be <code>DigestAuthenticationEntryPoint</code>, so that <code>DigestAuthenticationFilter</code> can obtain the correct <code>realmName</code> and <code>key</code> for digest calculations.</p>
                        </div>
                        <div class="paragraph">
                            <p>Like <code>BasicAuthenticationFilter</code>, if authentication is successful an <code>Authentication</code> request token will be placed into the <code>SecurityContextHolder</code>. If the authentication event was successful, or authentication was not attempted because the HTTP header did not contain a Digest Authentication request, the filter chain will continue as normal. The only time the filter chain will be interrupted is if authentication fails and the <code>AuthenticationEntryPoint</code> is called, as discussed in the previous paragraph.</p>
                        </div>
                        <div class="paragraph">
                            <p>Digest Authentication`s RFC offers a range of additional features to further increase security. For example, the nonce can be changed on every request. Despite this, Spring Security implementation was designed to minimise the complexity of the implementation (and the doubtless user agent incompatibilities that would emerge), and avoid needing to store server-side state. You are invited to review RFC 2617 if you wish to explore these features in more detail. As far as we are aware, Spring Security`s implementation does comply with the minimum standards of this RFC.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="remember-me"><a class="anchor" href="#remember-me"></a>5. Remember-Me Authentication</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="remember-me-overview"><a class="anchor" href="#remember-me-overview"></a>5.1. Overview</h3>
                    <div class="paragraph">
                        <p>Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions. This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations. One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens.</p>
                    </div>
                    <div class="paragraph">
                        <p>Note that both implemementations require a <code>UserDetailsService</code>. If you are using an authentication provider which doesn`t use a <code>UserDetailsService</code> (for example, the LDAP provider) then it won`t work unless you also have a <code>UserDetailsService</code> bean in your application context.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="remember-me-hash-token"><a class="anchor" href="#remember-me-hash-token"></a>5.2. Simple Hash-Based Token Approach</h3>
                    <div class="paragraph">
                        <p>This approach uses hashing to achieve a useful remember-me strategy. In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint txt language-txt"><code>base64(username + ":" + expirationTime + ":" +
md5Hex(username + ":" + expirationTime + ":" password + ":" + key))

username:          As identifiable to the `UserDetailsService`
password:          That matches the one in the retrieved UserDetails
expirationTime:    The date and time when the remember-me token expires, expressed in milliseconds
key:               A private key to prevent modification of the remember-me token</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>As such the remember-me token is valid only for the period specified, and provided that the username, password and key does not change. Notably, this has a potential security issue in that a captured remember-me token will be usable from any user agent until such time as the token expires. This is the same issue as with digest authentication. If a principal is aware a token has been captured, they can easily change their password and immediately invalidate all remember-me tokens on issue. If more significant security is needed you should use the approach described in the next section. Alternatively remember-me services should simply not be used at all.</p>
                    </div>
                    <div class="paragraph">
                        <p>If you are familiar with the topics discussed in the chapter on <a href="#ns-config">namespace configuration</a>, you can enable remember-me authentication just by adding the <code>&lt;remember-me&gt;</code> element:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;remember-me key="myAppKey"/&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The <code>UserDetailsService</code> will normally be selected automatically. If you have more than one in your application context, you need to specify which one should be used with the <code>user-service-ref</code> attribute, where the value is the name of your <code>UserDetailsService</code> bean.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="remember-me-persistent-token"><a class="anchor" href="#remember-me-persistent-token"></a>5.3. Persistent Token Approach</h3>
                    <div class="paragraph">
                        <p>This approach is based on the article <a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">http://jaspan.com/improved_persistent_login_cookie_best_practice</a> with some minor modifications <span class="footnote">[<a id="_footnoteref_18" class="footnote" href="#_footnote_18" title="View footnote.">18</a>]</span>. To use the this approach with namespace configuration, you would supply a datasource reference:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
  ...
  &lt;remember-me data-source-ref="someDataSource"/&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The database should contain a <code>persistent_logins</code> table, created using the following SQL (or equivalent):</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint ddl language-ddl"><code>create table persistent_logins (username varchar(64) not null,
                                series varchar(64) primary key,
                                token varchar(64) not null,
                                last_used timestamp not null)</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="remember-me-impls"><a class="anchor" href="#remember-me-impls"></a>5.4. Remember-Me Interfaces and Implementations</h3>
                    <div class="paragraph">
                        <p>Remember-me is used with <code>UsernamePasswordAuthenticationFilter</code>, and is implemented via hooks in the <code>AbstractAuthenticationProcessingFilter</code> superclass. It is also used within <code>BasicAuthenticationFilter</code>. The hooks will invoke a concrete <code>RememberMeServices</code> at the appropriate times. The interface looks like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);

void loginFail(HttpServletRequest request, HttpServletResponse response);

void loginSuccess(HttpServletRequest request, HttpServletResponse response,
    Authentication successfulAuthentication);</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Please refer to the JavaDocs for a fuller discussion on what the methods do, although note at this stage that <code>AbstractAuthenticationProcessingFilter</code> only calls the <code>loginFail()</code> and <code>loginSuccess()</code> methods. The <code>autoLogin()</code> method is called by <code>RememberMeAuthenticationFilter</code> whenever the <code>SecurityContextHolder</code> does not contain an <code>Authentication</code>. This interface therefore provides the underlying remember-me implementation with sufficient notification of authentication-related events, and delegates to the implementation whenever a candidate web request might contain a cookie and wish to be remembered. This design allows any number of remember-me implementation strategies. We`ve seen above that Spring Security provides two implementations. We`ll look at these in turn.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="tokenbasedremembermeservices"><a class="anchor" href="#tokenbasedremembermeservices"></a>5.4.1. TokenBasedRememberMeServices</h4>
                        <div class="paragraph">
                            <p>This implementation supports the simpler approach described in <a href="#remember-me-hash-token">Simple Hash-Based Token Approach</a>. <code>TokenBasedRememberMeServices</code> generates a <code>RememberMeAuthenticationToken</code>, which is processed by <code>RememberMeAuthenticationProvider</code>. A <code>key</code> is shared between this authentication provider and the <code>TokenBasedRememberMeServices</code>. In addition, <code>TokenBasedRememberMeServices</code> requires A UserDetailsService from which it can retrieve the username and password for signature comparison purposes, and generate the <code>RememberMeAuthenticationToken</code> to contain the correct <code>GrantedAuthority</code> s. Some sort of logout command should be provided by the application that invalidates the cookie if the user requests this. <code>TokenBasedRememberMeServices</code> also implements Spring Security`s <code>LogoutHandler</code> interface so can be used with <code>LogoutFilter</code> to have the cookie cleared automatically.</p>
                        </div>
                        <div class="paragraph">
                            <p>The beans required in an application context to enable remember-me services are as follows:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="rememberMeFilter" class=
 "org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter"&gt;
  &lt;property name="rememberMeServices" ref="rememberMeServices"/&gt;
  &lt;property name="authenticationManager" ref="theAuthenticationManager" /&gt;
&lt;/bean&gt;

&lt;bean id="rememberMeServices" class=
 "org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices"&gt;
  &lt;property name="userDetailsService" ref="myUserDetailsService"/&gt;
  &lt;property name="key" value="springRocks"/&gt;
&lt;/bean&gt;

&lt;bean id="rememberMeAuthenticationProvider" class=
 "org.springframework.security.authentication.rememberme.RememberMeAuthenticationProvider"&gt;
  &lt;property name="key" value="springRocks"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Don`t forget to add your <code>RememberMeServices</code> implementation to your <code>UsernamePasswordAuthenticationFilter.setRememberMeServices()</code> property, include the <code>RememberMeAuthenticationProvider</code> in your <code>AuthenticationManager.setProviders()</code> list, and add <code>RememberMeAuthenticationFilter</code> into your <code>FilterChainProxy</code> (typically immediately after your <code>UsernamePasswordAuthenticationFilter</code>).</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="persistenttokenbasedremembermeservices"><a class="anchor" href="#persistenttokenbasedremembermeservices"></a>5.4.2. PersistentTokenBasedRememberMeServices</h4>
                        <div class="paragraph">
                            <p>This class can be used in the same way as <code>TokenBasedRememberMeServices</code>, but it additionally needs to be configured with a <code>PersistentTokenRepository</code> to store the tokens. There are two standard implementations.</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><code>InMemoryTokenRepositoryImpl</code> which is intended for testing only.</p>
                                </li>
                                <li>
                                    <p><code>JdbcTokenRepositoryImpl</code> which stores the tokens in a database.</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>The database schema is described above in <a href="#remember-me-persistent-token">Persistent Token Approach</a>.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="csrf"><a class="anchor" href="#csrf"></a>6. Cross Site Request Forgery (CSRF)</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>This section discusses Spring Security`s <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery"> Cross Site Request Forgery (CSRF)</a> support.</p>
                </div>
                <div class="sect2">
                    <h3 id="csrf-attacks"><a class="anchor" href="#csrf-attacks"></a>6.1. CSRF Attacks</h3>
                    <div class="paragraph">
                        <p>Before we discuss how Spring Security can protect applications from CSRF attacks, we will explain what a CSRF attack is. Let`s take a look at a concrete example to get a better understanding.</p>
                    </div>
                    <div class="paragraph">
                        <p>Assume that your bank`s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint"><code>POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded

amount=100.00&amp;routingNumber=1234&amp;account=9876</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Now pretend you authenticate to your bank`s website and then, without logging out, visit an evil website. The evil website contains an HTML page with the following form:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;form action="https://bank.example.com/transfer" method="post"&gt;
  &lt;input type="hidden"
      name="amount"
      value="100.00"/&gt;
  &lt;input type="hidden"
      name="routingNumber"
      value="evilsRoutingNumber"/&gt;
  &lt;input type="hidden"
      name="account"
      value="evilsAccountNumber"/&gt;
  &lt;input type="submit"
      value="Win Money!"/&gt;
&lt;/form&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>You like to win money, so you click on the submit button. In the process, you have unintentionally transferred $100 to a malicious user. This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request.</p>
                    </div>
                    <div class="paragraph">
                        <p>Worst yet, this whole process could have been automated using JavaScript. This means you didn`t even need to click on the button. So how do we protect ourselves from such attacks?</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="synchronizer-token-pattern"><a class="anchor" href="#synchronizer-token-pattern"></a>6.2. Synchronizer Token Pattern</h3>
                    <div class="paragraph">
                        <p>The issue is that the HTTP request from the bank`s website and the request from the evil website are exactly the same. This means there is no way to reject requests coming from the evil website and allow requests coming from the bank`s website. To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide.</p>
                    </div>
                    <div class="paragraph">
                        <p>One solution is to use the <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern">Synchronizer Token Pattern</a>. This solution is to ensure that each request requires, in addition to our session cookie, a randomly generated token as an HTTP parameter. When a request is submitted, the server must look up the expected value for the parameter and compare it against the actual value in the request. If the values do not match, the request should fail.</p>
                    </div>
                    <div class="paragraph">
                        <p>We can relax the expectations to only require the token for each HTTP request that updates state. This can be safely done since the same origin policy ensures the evil site cannot read the response. Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked.</p>
                    </div>
                    <div class="paragraph">
                        <p>Let`s take a look at how our example would change. Assume the randomly generated token is present in an HTTP parameter named _csrf. For example, the request to transfer money would look like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint"><code>POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded

amount=100.00&amp;routingNumber=1234&amp;account=9876&amp;_csrf=&lt;secure-random&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>You will notice that we added the _csrf parameter with a random value. Now the evil website will not be able to guess the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual token to the expected token.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="when-to-use-csrf-protection"><a class="anchor" href="#when-to-use-csrf-protection"></a>6.3. When to use CSRF protection</h3>
                    <div class="paragraph">
                        <p>When you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-protection-and-json"><a class="anchor" href="#csrf-protection-and-json"></a>6.3.1. CSRF protection and JSON</h4>
                        <div class="paragraph">
                            <p>A common question is, but do I need to protect JSON requests made by javascript? The short answer is, it depends. However, you must be very careful as there are CSRF exploits that can impact JSON requests. For example, a malicious user can create a <a href="http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html">CSRF with JSON using the following form</a>:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;form action="https://bank.example.com/transfer" method="post" enctype="text/plain"&gt;
  &lt;input name='{"amount":100,"routingNumber":"evilsRoutingNumber","account":"evilsAccountNumber", "ignore_me":"' value='test"}' type='hidden'&gt;
  &lt;input type="submit"
      value="Win Money!"/&gt;
&lt;/form&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This will produce the following JSON structure</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint javascript language-javascript"><code>{ "amount": 100,
  "routingNumber": "evilsRoutingNumber",
  "account": "evilsAccountNumber",
  "ignore_me": "=test"
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>If an application were not validating the Content-Type, then it would be exposed to this exploit. Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with ".json" as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;form action="https://bank.example.com/transfer.json" method="post" enctype="text/plain"&gt;
  &lt;input name='{"amount":100,"routingNumber":"evilsRoutingNumber","account":"evilsAccountNumber", "ignore_me":"' value='test"}' type='hidden'&gt;
  &lt;input type="submit"
      value="Win Money!"/&gt;
&lt;/form&gt;</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-and-stateless-browser-applications"><a class="anchor" href="#csrf-and-stateless-browser-applications"></a>6.3.2. CSRF and Stateless Browser Applications</h4>
                        <div class="paragraph">
                            <p>What if my application is stateless? That doesn`t necessarily mean you are protected. In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks.</p>
                        </div>
                        <div class="paragraph">
                            <p>For example, consider an application uses a custom cookie that contains all the state within it for authentication instead of the JSESSIONID. When the CSRF attack is made the custom cookie will be sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example.</p>
                        </div>
                        <div class="paragraph">
                            <p>User`s using basic authentication are also vulnerable to CSRF attacks since the browser will automatically include the username password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="csrf-using"><a class="anchor" href="#csrf-using"></a>6.4. Using Spring Security CSRF Protection</h3>
                    <div class="paragraph">
                        <p>So what are the steps necessary to use Spring Security`s to protect our site against CSRF attacks? The steps to using Spring Security`s CSRF protection are outlined below:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p><a href="#csrf-use-proper-verbs">Use proper HTTP verbs</a></p>
                            </li>
                            <li>
                                <p><a href="#csrf-configure">Configure CSRF Protection</a></p>
                            </li>
                            <li>
                                <p><a href="#csrf-include-csrf-token">Include the CSRF Token</a></p>
                            </li>
                        </ul>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-use-proper-verbs"><a class="anchor" href="#csrf-use-proper-verbs"></a>6.4.1. Use proper HTTP verbs</h4>
                        <div class="paragraph">
                            <p>The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. Specifically, before Spring Security`s CSRF support can be of use, you need to be certain that your application is using PATCH, POST, PUT, and/or DELETE for anything that modifies state.</p>
                        </div>
                        <div class="paragraph">
                            <p>This is not a limitation of Spring Security`s support, but instead a general requirement for proper CSRF prevention. The reason is that including private information in an HTTP GET can cause the information to be leaked. See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3">RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI`s</a> for general guidance on using POST instead of GET for sensitive information.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-configure"><a class="anchor" href="#csrf-configure"></a>6.4.2. Configure CSRF Protection</h4>
                        <div class="paragraph">
                            <p>The next step is to include Spring Security`s CSRF protection within your application. Some frameworks handle invalid CSRF tokens by invaliding the user`s session, but this causes <a href="#csrf-logout">its own problems</a>. Instead by default Spring Security`s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the <a href="#access-denied-handler">AccessDeniedHandler</a> to process <code>InvalidCsrfTokenException</code> differently.</p>
                        </div>
                        <div class="paragraph">
                            <p>For passivity reasons, if you are using the XML configuration, CSRF protection must be explicitly enabled using the <a href="#nsa-csrf">&lt;csrf</a>&gt; element. Refer to the <a href="#nsa-csrf">&lt;csrf</a>&gt; element`s documentation for additional customizations.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p><a href="https://jira.springsource.org/browse/SEC-2347">SEC-2347</a> is logged to ensure Spring Security 4.x`s XML namespace configuration will enable CSRF protection by default.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;
    &lt;csrf /&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>CSRF protection is enabled by default with Java configuration. If you would like to disable CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() for additional customizations in how CSRF protection is configured.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable();
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-include-csrf-token"><a class="anchor" href="#csrf-include-csrf-token"></a>6.4.3. Include the CSRF Token</h4>
                        <div class="sect4">
                            <h5 id="csrf-include-csrf-token-form"><a class="anchor" href="#csrf-include-csrf-token-form"></a>Form Submissions</h5>
                            <div class="paragraph">
                                <p>The last step is to ensure that you include the CSRF token in all PATCH, POST, PUT, and DELETE methods. One way to approach this is to use the <code>_csrf</code> request attribute to obtain the current <code>CsrfToken</code>. An example of doing this with a JSP is shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;c:url var="logoutUrl" value="/logout"/&gt;
&lt;form action="${logoutUrl}"
    method="post"&gt;
  &lt;input type="submit"
    value="Log out" /&gt;
  &lt;input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/&gt;
&lt;/form&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>An easier approach is to use <a href="#the-csrfInput-tag">the csrfInput tag</a> from the Spring Security JSP tag library.</p>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            <div class="paragraph">
                                                <p>If you are using Spring MVC <code>&lt;form:form&gt;</code> tag or <a href="http://www.thymeleaf.org/whatsnew21.html#reqdata">Thymeleaf 2.1+</a>, and you replace <code>@EnableWebSecurity</code> with <code>@EnableWebMvcSecurity</code>, the <code>CsrfToken</code> is automatically included for you (using the <code>CsrfRequestDataValueProcessor</code>).</p>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="csrf-include-csrf-token-ajax"><a class="anchor" href="#csrf-include-csrf-token-ajax"></a>Ajax and JSON Requests</h5>
                            <div class="paragraph">
                                <p>If you using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;html&gt;
  &lt;head&gt;
    &lt;meta name="_csrf" content="${_csrf.token}"/&gt;
    &lt;!-- default header name is X-CSRF-TOKEN --&gt;
    &lt;meta name="_csrf_header" content="${_csrf.headerName}"/&gt;
    &lt;!-- ... --&gt;
  &lt;/head&gt;
  &lt;!-- ... --&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>Instead of manually creating the meta tags, you can use the simpler <a href="#the-csrfmetatags-tag">csrfMetaTags tag</a> from the Spring Security JSP tag library.</p>
                            </div>
                            <div class="paragraph">
                                <p>You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint javascript language-javascript"><code>$(function () {
  var token = $("meta[name='_csrf']").attr("content");
  var header = $("meta[name='_csrf_header']").attr("content");
  $(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
  });
});</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>As a alternative to jQuery, we recommend using <a href="http://cujojs.com/">cujoJS`s</a> rest.js. The <a href="https://github.com/cujojs/rest">rest.js</a> module provides advanced support for working with HTTP request and responses in RESTful ways. A core capability is the ability to contextualize the HTTP client adding behavior as needed by chaining interceptors on to the client.</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint javascript language-javascript"><code>var client = rest.chain(csrf, {
  token: $("meta[name='_csrf']").attr("content"),
  name: $("meta[name='_csrf_header']").attr("content")
});</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The configured client can be shared with any component of the application that needs to make a request to the CSRF protected resource. One significant different between rest.js and jQuery is that only requests made with the configured client will contain the CSRF token, vs jQuery where <em>all</em> requests will include the token. The ability to scope which requests receive the token helps guard against leaking the CSRF token to a third party. Please refer to the <a href="https://github.com/cujojs/rest/tree/master/docs">rest.js reference documentation</a> for more information on rest.js.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="csrf-caveats"><a class="anchor" href="#csrf-caveats"></a>6.5. CSRF Caveats</h3>
                    <div class="paragraph">
                        <p>There are a few caveats when implementing CSRF.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-timeouts"><a class="anchor" href="#csrf-timeouts"></a>6.5.1. Timeouts</h4>
                        <div class="paragraph">
                            <p>One issue is that the expected CSRF token is stored in the HttpSession, so as soon as the HttpSession expires your configured <code>AccessDeniedHandler</code> will receive a InvalidCsrfTokenException. If you are using the default <code>AccessDeniedHandler</code>, the browser will get an HTTP 403 and display a poor error message.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>One might ask why the expected <code>CsrfToken</code> isn`t stored in a cookie. This is because there are known exploits in which headers (i.e. specify the cookies) can be set by another domain. This is the same reason Ruby on Rails <a href="http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/">no longer skips CSRF checks when the header X-Requested-With is present</a>. See <a href="http://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html">this webappsec.org thread</a> for details on how to perform the exploit. Another disadvantage is that by removing the state (i.e. the timeout) you lose the ability to forcibly terminate the token if something got compromised.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>A simple way to mitigate an active user experiencing a timeout is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session.</p>
                        </div>
                        <div class="paragraph">
                            <p>Alternatively, specifying a custom <code>AccessDeniedHandler</code> allows you to process the <code>InvalidCsrfTokenException</code> anyway you like. For an example of how to customize the <code>AccessDeniedHandler</code> refer to the provided links for both <a href="#nsa-access-denied-handler">xml</a> and <a href="https://github.com/spring-projects/spring-security/blob/3.2.0.RC1/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy#L64">Java configuration</a>.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-login"><a class="anchor" href="#csrf-login"></a>6.5.2. Logging In</h4>
                        <div class="paragraph">
                            <p>In order to protect against <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests">forging log in requests</a> the log in form should be protected against CSRF attacks too. Since the <code>CsrfToken</code> is stored in HttpSession, this means an HttpSession will be created as soon as <code>CsrfToken</code> token attribute is accessed. While this sounds bad in a RESTful / stateless architecture the reality is that state is necessary to implement practical security. Without state, we have nothing we can do if a token is compromised. Practically speaking, the CSRF token is quite small in size and should have a negligible impact on our architecture.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-logout"><a class="anchor" href="#csrf-logout"></a>6.5.3. Logging Out</h4>
                        <div class="paragraph">
                            <p>Adding CSRF will update the LogoutFilter to only use HTTP POST. This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users.</p>
                        </div>
                        <div class="paragraph">
                            <p>One approach is to use a form for log out. If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST.</p>
                        </div>
                        <div class="paragraph">
                            <p>If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. For example, the following Java Configuration will perform logout with the URL /logout is requested with any HTTP method:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="csrf-multipart"><a class="anchor" href="#csrf-multipart"></a>6.5.4. Multipart (file upload)</h4>
                        <div class="paragraph">
                            <p>There are two options to using CSRF protection with multipart/form-data. Each option has its tradeoffs.</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><a href="#csrf-multipartfilter">Placing MultipartFilter before Spring Security</a></p>
                                </li>
                                <li>
                                    <p><a href="#csrf-include-csrf-token-in-action">Include CSRF token in action</a></p>
                                </li>
                            </ul>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>Before you integrate Spring Security`s CSRF protection with multipart file upload, ensure that you can upload without the CSRF protection first. More information about using multipart forms with Spring can be found within the <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart">17.10 Spring`s multipart (file upload) support</a> section of the Spring reference and the <a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html">MultipartFilter javadoc</a>.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="sect4">
                            <h5 id="csrf-multipartfilter"><a class="anchor" href="#csrf-multipartfilter"></a>Placing MultipartFilter before Spring Security</h5>
                            <div class="paragraph">
                                <p>The first option is to ensure that the <code>MultipartFilter</code> is specified before the Spring Security filter. Specifying the <code>MultipartFilter</code> before the Spring Security filter means that there is no authorization for invoking the <code>MultipartFilter</code> which means anyone can place temporary files on your server. However, only authorized users will be able to submit a File that is processed by your application. In general, this is the recommended approach because the temporary file upload should have a negligble impact on most servers.</p>
                            </div>
                            <div class="paragraph">
                                <p>To ensure <code>MultipartFilter</code> is specified before the Spring Security filter with java configuration, users can override beforeSpringSecurityFilterChain as shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
        insertFilters(servletContext, new MultipartFilter());
    }
}</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>To ensure <code>MultipartFilter</code> is specified before the Spring Security filter with XML configuration, users can ensure the &lt;filter-mapping&gt; element of the <code>MultipartFilter</code> is placed before the springSecurityFilterChain within the web.xml as shown below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;filter&gt;
    &lt;filter-name&gt;MultipartFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;org.springframework.web.multipart.support.MultipartFilter&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter&gt;
    &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
    &lt;filter-name&gt;MultipartFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
&lt;filter-mapping&gt;
    &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;</code></pre>
                                </div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="csrf-include-csrf-token-in-action"><a class="anchor" href="#csrf-include-csrf-token-in-action"></a>Include CSRF token in action</h5>
                            <div class="paragraph">
                                <p>If allowing unauthorized users to upload temporariy files is not acceptable, an alternative is to place the <code>MultipartFilter</code> after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. An example with a jsp is shown below</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data"&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The disadvantage to this approach is that query parameters can be leaked. More genearlly, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. Additional information can be found in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3">RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI`s</a>.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="hiddenhttpmethodfilter"><a class="anchor" href="#hiddenhttpmethodfilter"></a>6.5.5. HiddenHttpMethodFilter</h4>
                        <div class="paragraph">
                            <p>The HiddenHttpMethodFilter should be placed before the Spring Security filter. In general this is true, but it could have additional implications when protecting against CSRF attacks.</p>
                        </div>
                        <div class="paragraph">
                            <p>Note that the HiddenHttpMethodFilter only overrides the HTTP method on a POST, so this is actually unlikely to cause any real problems. However, it is still best practice to ensure it is placed before Spring Security`s filters.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="overriding-defaults"><a class="anchor" href="#overriding-defaults"></a>6.6. Overriding Defaults</h3>
                    <div class="paragraph">
                        <p>Spring Security`s goal is to provide defaults that protect your users from exploits. This does not mean that you are forced to accept all of its defaults.</p>
                    </div>
                    <div class="paragraph">
                        <p>For example, you can provide a custom CsrfTokenRepository to override the way in which the <code>CsrfToken</code> is stored.</p>
                    </div>
                    <div class="paragraph">
                        <p>You can also specify a custom RequestMatcher to determine which requests are protected by CSRF (i.e. perhaps you don`t care if log out is exploited). In short, if Spring Security`s CSRF protection doesn`t behave exactly as you want it, you are able to customize the behavior. Refer to the <a href="#nsa-csrf">&lt;csrf&gt;</a> documentation for details on how to make these customizations with XML and the <code>CsrfConfigurer</code> javadoc for details on how to make these customizations when using Java configuration.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="headers"><a class="anchor" href="#headers"></a>7. Security HTTP Response Headers</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>This section discusses Spring Security`s support for adding various security headers to the response.</p>
                </div>
                <div class="sect2">
                    <h3 id="default-security-headers"><a class="anchor" href="#default-security-headers"></a>7.1. Default Security Headers</h3>
                    <div class="paragraph">
                        <p>Spring Security allows users to easily inject the default security headers to assist in protecting their application. The following is a list of the current <em>Default Security Headers</em> provided by Spring Security:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p><a href="#headers-cache-control">Cache Control</a></p>
                            </li>
                            <li>
                                <p><a href="#headers-content-type-options">Content Type Options</a></p>
                            </li>
                            <li>
                                <p><a href="#headers-hsts">HTTP Strict Transport Security</a></p>
                            </li>
                            <li>
                                <p><a href="#headers-frame-options">X-Frame-Options</a></p>
                            </li>
                            <li>
                                <p><a href="#headers-xss-protection">X-XSS-Protection</a></p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged. For passivity reasons, if you are using Spring Security`s XML namespace support, you must explicitly enable the security headers. All of the default headers can be easily added using the <a href="#nsa-headers">&lt;headers</a>&gt; element with no child elements:</p>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    <div class="paragraph">
                                        <p><a href="https://jira.springsource.org/browse/SEC-2348">SEC-2348</a> is logged to ensure Spring Security 4.x`s XML namespace configuration will enable Security headers by default.</p>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers /&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Alternatively, you can choose to explicitly list the headers you wish to include. For example, the following is the same the previous configuration. Removing any of the elements will remove that header from the responses.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;cache-control /&gt;
        &lt;content-type-options /&gt;
        &lt;hsts /&gt;
        &lt;frame-options /&gt;
        &lt;xss-protection /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>If you are using Spring Security`s Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers().disable();
  }
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>As soon as you specify any headers that should be included, then only those headers will be include. For example, the following configuration will include support for <a href="#headers-cache-control">Cache Control</a> and <a href="#headers-frame-options">X-Frame-Options</a> only.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .cacheControl()
        .frameOptions();
  }
}</code></pre>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-cache-control"><a class="anchor" href="#headers-cache-control"></a>7.1.1. Cache Control</h4>
                        <div class="paragraph">
                            <p>In the past Spring Security required you to provide your own cache control for your web application. This seemed reasonable at the time, but browser caches have evolved to include caches for secure connections as well. This means that a user may view an authenticated page, log out, and then a malicious user can use the browser history to view the cached page. To help mitigate this Spring Security has added cache control support which will insert the following headers into you response.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Simply adding the <a href="#nsa-headers">&lt;headers</a>&gt; element with no child elements will automatically add Cache Control and quite a few other protections. However, if you only want cache control, you can enable this feature using Spring Security`s XML namespace with the <a href="#nsa-cache-control">&lt;cache-control</a>&gt; element.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;cache-control /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Similarly, you can enable only cache control within Java Configuration with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .cacheControl();
  }
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>If you actually want to cache specific responses, your application can selectively invoke <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader(java.lang.String,java.lang.String)">HttpServletResponse.setHeader(String,String)</a> to override the header set by Spring Security. This is useful to ensure things like CSS, JavaScript, and images are properly cached.</p>
                        </div>
                        <div class="paragraph">
                            <p>When using Spring Web MVC, this is typically done within your configuration. For example, the following configuration will ensure that the cache headers are set for all of your resources:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
            .addResourceHandler("/resources/**")
            .addResourceLocations("/resources/")
            .setCachePeriod(31556926);
    }

    // ...
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-content-type-options"><a class="anchor" href="#headers-content-type-options"></a>7.1.2. Content Type Options</h4>
                        <div class="paragraph">
                            <p>Historically browsers, including Internet Explorer, would try to guess the content type of a request using <a href="http://en.wikipedia.org/wiki/Content_sniffing">content sniffing</a>. This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then execute it.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>There are many additional things one should do (i.e. only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, etc) when allowing content to be uploaded. However, these measures are out of the scope of what Spring Security provides. It is also important to point out when disabling content sniffing, you must specify the content type in order for things to work properly.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>The problem with content sniffing is that this allowed malicious users to use polyglots (i.e. a file that is valid as multiple content types) to execute XSS attacks. For example, some sites may allow users to submit a valid postscript document to a website and view it. A malicious user might create a <a href="http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf">postscript document that is also a valid JavaScript file</a> and execute a XSS attack with it.</p>
                        </div>
                        <div class="paragraph">
                            <p>Content sniffing can be disabled by adding the following header to our response:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>X-Content-Type-Options: nosniff</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Just as with the cache control element, the nosniff directive is added by default when using the &lt;headers&gt; element with no child elements. However, if you want more control over which headers are added you can use the <a href="#nsa-content-type-options">&lt;content-type-options</a>&gt; element as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;content-type-options /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The X-Content-Type-Options header is added by default with Spring Security Java configuration. If you want more control over the headers, you can explicitly specify the content type options with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .contentTypeOptions();
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-hsts"><a class="anchor" href="#headers-hsts"></a>7.1.3. HTTP Strict Transport Security (HSTS)</h4>
                        <div class="paragraph">
                            <p>When you type in your bank`s website, do you enter mybank.example.com or do you enter <a href="https://mybank.example.com">https://mybank.example.com</a>? If you omit the https protocol, you are potentially vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">Man in the Middle attacks</a>. Even if the website performs a redirect to <a href="https://mybank.example.com">https://mybank.example.com</a> a malicious user could intercept the initial HTTP request and manipulate the response (i.e. redirect to <a href="https://mibank.example.com">https://mibank.example.com</a> and steal their credentials).</p>
                        </div>
                        <div class="paragraph">
                            <p>Many users omit the https protocol and this is why <a href="http://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security (HSTS)</a> was created. Once mybank.example.com is added as a <a href="http://tools.ietf.org/html/rfc6797#section-5.1">HSTS host</a>, a browser can know ahead of time that any request to mybank.example.com should be interpreted as <a href="https://mybank.example.com">https://mybank.example.com</a>. This greatly reduces the possibility of a Man in the Middle attack occurring.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>In accordance with <a href="http://tools.ietf.org/html/rfc6797#section-7.2">RFC6797</a>, the HSTS header is only injected into HTTPS responses. In order for the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate).</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>One way for a site to be marked as a HSTS host is to have the host preloaded into the browser. Another is to add the "Strict-Transport-Security" header to the response. For example the following would instruct the browser to treat the domain as an HSTS host for a year (there are approximately 31536000 seconds in a year):</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>Strict-Transport-Security: max-age=31536000 ; includeSubDomains</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The optional includeSubDomains directive instructs Spring Security that subdomains (i.e. secure.mybank.example.com) should also be treated as an HSTS domain.</p>
                        </div>
                        <div class="paragraph">
                            <p>As with the other headers, Spring Security adds the previous header to the response when the &lt;headers&gt; element is specified with no child elements. It is also automatically added when you are using Java Configuration. You can also only use HSTS headers with the <a href="#nsa-hsts">&lt;hsts</a>&gt; element as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;hsts /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Similarly, you can enable only HSTS headers with Java Configuration:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .httpStrictTransportSecurity();
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-frame-options"><a class="anchor" href="#headers-frame-options"></a>7.1.4. X-Frame-Options</h4>
                        <div class="paragraph">
                            <p>Allowing your website to be added to a frame can be a security issue. For example, using clever CSS styling users could be tricked into clicking on something that they were not intending (<a href="http://www.youtube.com/watch?v=3mk0RySeNsU">video demo</a>). For example, a user that is logged into their bank might click a button that grants access to other users. This sort of attack is known as <a href="http://en.wikipedia.org/wiki/Clickjacking">Clickjacking</a>.</p>
                        </div>
                        <div class="admonitionblock note">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-note" title="Note"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>Another modern approach to dealing with clickjacking is using a <a href="http://www.w3.org/TR/CSP/">Content Security Policy</a>. Spring Security does not provide support for this as the specification is not released and it is quite a bit more complicated. However, you could use the <a href="#headers-static">static headers</a> feature to implement this. To stay up to date with this issue and to see how you can implement it with Spring Security refer to <a href="https://jira.springsource.org/browse/SEC-2117">SEC-2117</a></p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="paragraph">
                            <p>There are a number ways to mitigate clickjacking attacks. For example, to protect legacy browsers from clickjacking attacks you can use <a href="https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script">frame breaking code</a>. While not perfect, the frame breaking code is the best you can do for the legacy browsers.</p>
                        </div>
                        <div class="paragraph">
                            <p>A more modern approach to address clickjacking is to use <a href="https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options">X-Frame-Options</a> header:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>X-Frame-Options: DENY</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The X-Frame-Options response header instructs the browser to prevent any site with this header in the response from being rendered within a frame. As with the other response headers, this is automatically included when the &lt;headers&gt; element is specified with no child elements. You can also explicitly specify the <a href="#nsa-frame-options">frame-options</a> element to control which headers are added to the response.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;frame-options /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Similarly, you can enable only frame options within Java Configuration with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .frameOptions();
  }
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>If you want to change the value for the X-Frame-Options header, then you can use a <a href="#headers-headers-writer">XFrameOptionsHeaderWriter instance</a>.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-xss-protection"><a class="anchor" href="#headers-xss-protection"></a>7.1.5. X-XSS-Protection</h4>
                        <div class="paragraph">
                            <p>Some browsers have built in support for filtering out <a href="https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)">reflected XSS attacks</a>. This is by no means full proof, but does assist in XSS protection.</p>
                        </div>
                        <div class="paragraph">
                            <p>The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. At times, this type of replacement can become a <a href="http://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/">XSS vulnerability in itself</a>. Instead, it is best to block the content rather than attempt to fix it. To do this we can add the following header:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>X-XSS-Protection: 1; mode=block</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This header is included by default when the &lt;headers&gt; element is specified with no child elements. We can explicitly state it using the <a href="#nsa-xss-protection">xss-protection</a> element as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;xss-protection /&gt;
    &lt;/headers&gt;
&lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Similarly, you can enable only xss protection within Java Configuration with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .xssProtection();
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="headers-custom"><a class="anchor" href="#headers-custom"></a>7.2. Custom Headers</h3>
                    <div class="paragraph">
                        <p>Spring Security has mechanisms to make it convenient to add the more common security headers to your application. However, it also provides hooks to enable adding custom headers.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-static"><a class="anchor" href="#headers-static"></a>7.2.1. Static Headers</h4>
                        <div class="paragraph">
                            <p>There may be times you wish to inject custom security headers into your application that are not supported out of the box. For example, perhaps you wish to have early support for <a href="http://www.w3.org/TR/CSP/">Content Security Policy</a> in order to ensure that resources are only loaded from the same origin. Since support for Content Security Policy has not been finalized, browsers use one of two common extension headers to implement the feature. This means we will need to inject the policy twice. An example of the headers can be seen below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>X-Content-Security-Policy: default-src 'self'
X-WebKit-CSP: default-src 'self'</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>When using the XML namespace, these headers can be added to the response using the <a href="#nsa-header">&lt;header</a>&gt; element as shown below:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
      &lt;!-- ... --&gt;

      &lt;headers&gt;
          &lt;header name="X-Content-Security-Policy" value="default-src 'self'"/&gt;
          &lt;header name="X-WebKit-CSP" value="default-src 'self'"/&gt;
      &lt;/headers&gt;
  &lt;/http&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Similarly, the headers could be added to the response using Java Configuration as shown in the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","default-src 'self'"))
        .addHeaderWriter(new StaticHeadersWriter("X-WebKit-CSP","default-src 'self'"));
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-writer"><a class="anchor" href="#headers-writer"></a>7.2.2. Headers Writer</h4>
                        <div class="paragraph">
                            <p>When the namespace or Java configuration does not support the headers you want, you can create a custom <code>HeadersWriter</code> instance or even provide a custom implementation of the <code>HeadersWriter</code>.</p>
                        </div>
                        <div class="paragraph">
                            <p>Let`s take a look at an example of using an custom instance of <code>XFrameOptionsHeaderWriter</code>. Perhaps you want to allow framing of content for the same origin. This is easily supported by setting the <a href="#nsa-frame-options-policy">policy</a> attribute to "SAMEORIGIN", but let`s take a look at a more explicit example using the <a href="#nsa-header-ref">ref</a> attribute.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;header ref="frameOptionsWriter"/&gt;
    &lt;/headers&gt;
&lt;/http&gt;
&lt;!-- Requires the c-namespace.
  See http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-c-namespace
--&gt;
&lt;beans:bean id="frameOptionsWriter"
    class="org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"
    c:frameOptionsMode="SAMEORIGIN"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>We could also restrict framing of content to the same origin with Java configuration:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN));
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="headers-delegatingrequestmatcherheaderwriter"><a class="anchor" href="#headers-delegatingrequestmatcherheaderwriter"></a>7.2.3. DelegatingRequestMatcherHeaderWriter</h4>
                        <div class="paragraph">
                            <p>At times you may want to only write a header for certain requests. For example, perhaps you want to only protect your log in page from being framed. You could use the <code>DelegatingRequestMatcherHeaderWriter</code> to do so. When using the XML namespace configuration, this can be done with the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
    &lt;!-- ... --&gt;

    &lt;headers&gt;
        &lt;header ref="headerWriter"/&gt;
    &lt;/headers&gt;
&lt;/http&gt;

&lt;beans:bean id="headerWriter"
    class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter"&gt;
    &lt;beans:constructor-arg&gt;
        &lt;bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
            c:pattern="/login"/&gt;
    &lt;/beans:constructor-arg&gt;
    &lt;beans:constructor-arg&gt;
        &lt;beans:bean
            class="org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"/&gt;
    &lt;/beans:constructor-arg&gt;
&lt;/beans:bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>We could also prevent framing of content to the log in page using java configuration:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    RequestMatcher matcher = new AntPathRequestMatcher("/login");
    DelegatingRequestMatcherHeaderWriter headerWriter =
        new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter());
    http
      // ...
      .headers()
        .addHeaderWriter(headerWriter);
  }
}</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="session-mgmt"><a class="anchor" href="#session-mgmt"></a>8. Session Management</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>HTTP session related functonality is handled by a combination of the <code>SessionManagementFilter</code> and the <code>SessionAuthenticationStrategy</code> interface, which the filter delegates to. Typical usage includes session-fixation protection attack prevention, detection of session timeouts and restrictions on how many sessions an authenticated user may have open concurrently.</p>
                </div>
                <div class="sect2">
                    <h3 id="sessionmanagementfilter"><a class="anchor" href="#sessionmanagementfilter"></a>8.1. SessionManagementFilter</h3>
                    <div class="paragraph">
                        <p>The <code>SessionManagementFilter</code> checks the contents of the <code>SecurityContextRepository</code> against the current contents of the <code>SecurityContextHolder</code> to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me <span class="footnote">[<a id="_footnoteref_19" class="footnote" href="#_footnote_19" title="View footnote.">19</a>]</span>. If the repository contains a security context, the filter does nothing. If it doesn`t, and the thread-local <code>SecurityContext</code> contains a (non-anonymous) <code>Authentication</code> object, the filter assumes they have been authenticated by a previous filter in the stack. It will then invoke the configured <code>SessionAuthenticationStrategy</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured`InvalidSessionStrategy`, if one is set. The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation`SimpleRedirectInvalidSessionStrategy`. The latter is also used when configuring an invalid session URL through the namespace,<a href="#ns-session-mgmt">as described earlier</a>.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="sessionauthenticationstrategy"><a class="anchor" href="#sessionauthenticationstrategy"></a>8.2. SessionAuthenticationStrategy</h3>
                    <div class="paragraph">
                        <p><code>SessionAuthenticationStrategy</code> is used by both <code>SessionManagementFilter</code> and <code>AbstractAuthenticationProcessingFilter</code>, so if you are using a customized form-login class, for example, you will need to inject it into both of these. In this case, a typical configuration, combining the namespace and custom beans might look like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;http&gt;
  &lt;custom-filter position="FORM_LOGIN_FILTER" ref="myAuthFilter" /&gt;
  &lt;session-management session-authentication-strategy-ref="sas"/&gt;
&lt;/http&gt;

&lt;beans:bean id="myAuthFilter" class=
  "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"&gt;
    &lt;beans:property name="sessionAuthenticationStrategy" ref="sas" /&gt;
    ...
&lt;/beans:bean&gt;

&lt;beans:bean id="sas" class=
  "org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy" /&gt;
</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Note that the use of the default, <code>SessionFixationProtectionStrategy</code> may cause issues if you are storing beans in the session which implement <code>HttpSessionBindingListener</code>, including Spring session-scoped beans. See the Javadoc for this class for more information.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="concurrent-sessions"><a class="anchor" href="#concurrent-sessions"></a>8.3. Concurrency Control</h3>
                    <div class="paragraph">
                        <p>Spring Security is able to prevent a principal from concurrently authenticating to the same application more than a specified number of times. Many ISVs take advantage of this to enforce licensing, whilst network administrators like this feature because it helps prevent people from sharing login names. You can, for example, stop user"Batman" from logging onto the web application from two different sessions. You can either expire their previous login or you can report an error when they try to log in again, preventing the second login. Note that if you are using the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) will not be able to log in again until their original session expires.</p>
                    </div>
                    <div class="paragraph">
                        <p>Concurrency control is supported by the namespace, so please check the earlier namespace chapter for the simplest configuration. Sometimes you need to customize things though.</p>
                    </div>
                    <div class="paragraph">
                        <p>The implementation uses a specialized version of <code>SessionAuthenticationStrategy</code>, called <code>ConcurrentSessionControlAuthenticationStrategy</code>.</p>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    <div class="paragraph">
                                        <p>Previously the concurrent authentication check was made by the <code>ProviderManager</code>, which could be injected with a <code>ConcurrentSessionController</code>. The latter would check if the user was attempting to exceed the number of permitted sessions. However, this approach required that an HTTP session be created in advance, which is undesirable. In Spring Security 3, the user is first authenticated by the <code>AuthenticationManager</code> and once they are successfully authenticated, a session is created and the check is made whether they are allowed to have another session open.</p>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="paragraph">
                        <p>To use concurrent session support, you`ll need to add the following to <code>web.xml</code>:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
  &lt;listener&gt;
    &lt;listener-class&gt;
      org.springframework.security.web.session.HttpSessionEventPublisher
    &lt;/listener-class&gt;
  &lt;/listener&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>In addition, you will need to add the <code>ConcurrentSessionFilter</code> to your <code>FilterChainProxy</code>. The <code>ConcurrentSessionFilter</code> requires two properties, <code>sessionRegistry</code>, which generally points to an instance of <code>SessionRegistryImpl</code>, and <code>expiredUrl</code>, which points to the page to display when a session has expired. A configuration using the namespace to create the <code>FilterChainProxy</code> and other default beans might look like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;http&gt;
  &lt;custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" /&gt;
  &lt;custom-filter position="FORM_LOGIN_FILTER" ref="myAuthFilter" /&gt;

  &lt;session-management session-authentication-strategy-ref="sas"/&gt;
&lt;/http&gt;

&lt;beans:bean id="concurrencyFilter"
   class="org.springframework.security.web.session.ConcurrentSessionFilter"&gt;
  &lt;beans:property name="sessionRegistry" ref="sessionRegistry" /&gt;
  &lt;beans:property name="expiredUrl" value="/session-expired.htm" /&gt;
&lt;/beans:bean&gt;

&lt;beans:bean id="myAuthFilter" class=
   "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"&gt;
  &lt;beans:property name="sessionAuthenticationStrategy" ref="sas" /&gt;
  &lt;beans:property name="authenticationManager" ref="authenticationManager" /&gt;
&lt;/beans:bean&gt;

&lt;beans:bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy"&gt;
  &lt;beans:constructor-arg&gt;
    &lt;beans:list&gt;
      &lt;beans:bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy"&gt;
        &lt;beans:constructor-arg ref="sessionRegistry"/&gt;
        &lt;beans:property name="maximumSessions" value="1" /&gt;
        &lt;beans:property name="exceptionIfMaximumExceeded" value="true" /&gt;
      &lt;/beans:bean&gt;
      &lt;beans:bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy"&gt;
      &lt;/beans:bean&gt;
      &lt;beans:bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy"&gt;
        &lt;beans:constructor-arg ref="sessionRegistry"/&gt;
      &lt;/beans:bean&gt;
    &lt;/beans:list&gt;
  &lt;/beans:constructor-arg&gt;
&lt;/beans:bean&gt;

&lt;beans:bean id="sessionRegistry"
    class="org.springframework.security.core.session.SessionRegistryImpl" /&gt;
</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Adding the listener to <code>web.xml</code> causes an <code>ApplicationEvent</code> to be published to the Spring <code>ApplicationContext</code> every time a <code>HttpSession</code> commences or terminates. This is critical, as it allows the <code>SessionRegistryImpl</code> to be notified when a session ends. Without it, a user will never be able to log back in again once they have exceeded their session allowance, even if they log out of another session or it times out.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="list-authenticated-principals"><a class="anchor" href="#list-authenticated-principals"></a>8.3.1. Querying the SessionRegistry for currently authenticated users and their sessions</h4>
                        <div class="paragraph">
                            <p>Setting up concurrency-control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the <code>SessionRegistry</code> which you can use directly within your application, so even if you don`t want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. You can set the <code>maximumSession</code> property to -1 to allow unlimited sessions. If you`re using the namespace, you can set an alias for the internally-created <code>SessionRegistry</code> using the <code>session-registry-alias</code> attribute, providing a reference which you can inject into your own beans.</p>
                        </div>
                        <div class="paragraph">
                            <p>The <code>getAllPrincipals()</code> method supplies you with a list of the currently authenticated users. You can list a user`s sessions by calling the <code>getAllSessions(Object principal, boolean includeExpiredSessions)</code> method, which returns a list of <code>SessionInformation</code> objects. You can also expire a user`s session by calling <code>expireNow()</code> on a <code>SessionInformation</code> instance. When the user returns to the application, they will be prevented from proceeding. You may find these methods useful in an administration application, for example. Have a look at the Javadoc for more information.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="anonymous"><a class="anchor" href="#anonymous"></a>9. Anonymous Authentication</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="anonymous-overview"><a class="anchor" href="#anonymous-overview"></a>9.1. Overview</h3>
                    <div class="paragraph">
                        <p>It`s generally considered good security practice to adopt a "deny-by-default" where you explicitly specify what is allowed and disallow everything else. Defining what is accessible to unauthenticated users is a similar situation, particularly for web applications. Many sites require that users must be authenticated for anything other than a few URLs (for example the home and login pages). In this case it is easiest to define access configuration attributes for these specific URLs rather than have for every secured resource. Put differently, sometimes it is nice to say <code>ROLE_SOMETHING</code> is required by default and only allow certain exceptions to this rule, such as for login, logout and home pages of an application. You could also omit these pages from the filter chain entirely, thus bypassing the access control checks, but this may be undesirable for other reasons, particularly if the pages behave differently for authenticated users.</p>
                    </div>
                    <div class="paragraph">
                        <p>This is what we mean by anonymous authentication. Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. Spring Security`s anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API calls such as <code>getCallerPrincipal</code>, for example, will still return null even though there is actually an anonymous authentication object in the <code>SecurityContextHolder</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>There are other situations where anonymous authentication is useful, such as when an auditing interceptor queries the <code>SecurityContextHolder</code> to identify which principal was responsible for a given operation. Classes can be authored more robustly if they know the <code>SecurityContextHolder</code> always contains an <code>Authentication</code> object, and never <code>null</code>.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="anonymous-config"><a class="anchor" href="#anonymous-config"></a>9.2. Configuration</h3>
                    <div class="paragraph">
                        <p>Anonymous authentication support is provided automatically when using the HTTP configuration Spring Security 3.0 and can be customized (or disabled) using the <code>&lt;anonymous&gt;</code> element. You don`t need to configure the beans described here unless you are using traditional bean configuration.</p>
                    </div>
                    <div class="paragraph">
                        <p>Three classes that together provide the anonymous authentication feature. <code>AnonymousAuthenticationToken</code> is an implementation of <code>Authentication</code>, and stores the <code>GrantedAuthority</code> s which apply to the anonymous principal. There is a corresponding <code>AnonymousAuthenticationProvider</code>, which is chained into the <code>ProviderManager</code> so that <code>AnonymousAuthenticationToken</code> s are accepted. Finally, there is an <code>AnonymousAuthenticationFilter</code>, which is chained after the normal authentication mechanisms and automatically adds an <code>AnonymousAuthenticationToken</code> to the <code>SecurityContextHolder</code> if there is no existing <code>Authentication</code> held there. The definition of the filter and authentication provider appears as follows:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="anonymousAuthFilter"
    class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter"&gt;
  &lt;property name="key" value="foobar"/&gt;
  &lt;property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/&gt;
&lt;/bean&gt;

&lt;bean id="anonymousAuthenticationProvider"
    class="org.springframework.security.authentication.AnonymousAuthenticationProvider"&gt;
  &lt;property name="key" value="foobar"/&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The <code>key</code> is shared between the filter and authentication provider, so that tokens created by the former are accepted by the latter <span class="footnote">[<a id="_footnoteref_20" class="footnote" href="#_footnote_20" title="View footnote.">20</a>]</span>. The <code>userAttribute</code> is expressed in the form of <code>usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]</code>. This is the same syntax as used after the equals sign for`InMemoryDaoImpl`'s <code>userMap</code> property.</p>
                    </div>
                    <div class="paragraph">
                        <p>As explained earlier, the benefit of anonymous authentication is that all URI patterns can have security applied to them. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="filterSecurityInterceptor"
    class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/&gt;
  &lt;property name="securityMetadata"&gt;
    &lt;security:filter-security-metadata-source&gt;
      &lt;security:intercept-url pattern='/index.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/&gt;
      &lt;security:intercept-url pattern='/hello.htm' access='ROLE_ANONYMOUS,ROLE_USER'/&gt;
      &lt;security:intercept-url pattern='/logoff.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/&gt;
      &lt;security:intercept-url pattern='/login.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/&gt;
      &lt;security:intercept-url pattern='/**' access='ROLE_USER'/&gt;
    &lt;/security:filter-security-metadata-source&gt;" +
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="anonymous-auth-trust-resolver"><a class="anchor" href="#anonymous-auth-trust-resolver"></a>9.3. AuthenticationTrustResolver</h3>
                    <div class="paragraph">
                        <p>Rounding out the anonymous authentication discussion is the <code>AuthenticationTrustResolver</code> interface, with its corresponding <code>AuthenticationTrustResolverImpl</code> implementation. This interface provides an <code>isAnonymous(Authentication)</code> method, which allows interested classes to take into account this special type of authentication status. The <code>ExceptionTranslationFilter</code> uses this interface in processing <code>AccessDeniedException</code> s. If an <code>AccessDeniedException</code> is thrown, and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter will instead commence the <code>AuthenticationEntryPoint</code> so the principal can authenticate properly. This is a necessary distinction, otherwise principals would always be deemed "authenticated" and never be given an opportunity to login via form, basic, digest or some other normal authentication mechanism.</p>
                    </div>
                    <div class="paragraph">
                        <p>You will often see the <code>ROLE_ANONYMOUS</code> attribute in the above interceptor configuration replaced with <code>IS_AUTHENTICATED_ANONYMOUSLY</code>, which is effectively the same thing when defining access controls. This is an example of the use of the <code>AuthenticatedVoter</code> which we will see in the <a href="#authz-authenticated-voter">authorization chapter</a>. It uses an <code>AuthenticationTrustResolver</code> to process this particular configuration attribute and grant access to anonymous users. the <code>AuthenticatedVoter</code> approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users. If you don`t need this functionality though, then you can stick with <code>ROLE_ANONYMOUS</code>, which will be processed by Spring Security`s standard <code>RoleVoter</code>.</p>
                    </div>
                </div>
            </div>
        </div>
        <h1 id="authorization" class="sect0"><a class="anchor" href="#authorization"></a>Authorization</h1>
        <div class="paragraph">
            <p>The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. Irrespective of how you choose to authenticate - whether using a Spring Security-provided mechanism and provider, or integrating with a container or other non-Spring Security authentication authority - you will find the authorization services can be used within your application in a consistent and simple way.</p>
        </div>
        <div class="paragraph">
            <p>In this part we`ll explore the different <code>AbstractSecurityInterceptor</code> implementations, which were introduced in Part I. We then move on to explore how to fine-tune authorization through use of domain access control lists.</p>
        </div>
        <div class="sect1">
            <h2 id="authz-arch"><a class="anchor" href="#authz-arch"></a>1. Authorization Architecture</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="authz-authorities"><a class="anchor" href="#authz-authorities"></a>1.1. Authorities</h3>
                    <div class="paragraph">
                        <p>As we saw in the <a href="#tech-granted-authority">technical overview</a>, all <code>Authentication</code> implementations store a list of <code>GrantedAuthority</code> objects. These represent the authorities that have been granted to the principal. the <code>GrantedAuthority</code> objects are inserted into the <code>Authentication</code> object by the <code>AuthenticationManager</code> and are later read by <code>AccessDecisionManager</code> s when making authorization decisions.</p>
                    </div>
                    <div class="paragraph">
                        <p><code>GrantedAuthority</code> is an interface with only one method:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>
  String getAuthority();
</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>This method allows
                            <code>AccessDecisionManager</code> s to obtain a precise <code>String</code> representation of the <code>GrantedAuthority</code>. By returning a representation as a <code>String</code>, a <code>GrantedAuthority</code> can be easily "read" by most <code>AccessDecisionManager</code> s. If a <code>GrantedAuthority</code> cannot be precisely represented as a <code>String</code>, the <code>GrantedAuthority</code> is considered "complex" and <code>getAuthority()</code> must return <code>null</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>An example of a "complex" <code>GrantedAuthority</code> would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. Representing this complex <code>GrantedAuthority</code> as a <code>String</code> would be quite difficult, and as a result the <code>getAuthority()</code> method should return <code>null</code>. This will indicate to any <code>AccessDecisionManager</code> that it will need to specifically support the <code>GrantedAuthority</code> implementation in order to understand its contents.</p>
                    </div>
                    <div class="paragraph">
                        <p>Spring Security includes one concrete <code>GrantedAuthority</code> implementation, <code>GrantedAuthorityImpl</code>. This allows any user-specified <code>String</code> to be converted into a <code>GrantedAuthority</code>. All <code>AuthenticationProvider</code> s included with the security architecture use <code>GrantedAuthorityImpl</code> to populate the <code>Authentication</code> object.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="authz-pre-invocation"><a class="anchor" href="#authz-pre-invocation"></a>1.2. Pre-Invocation Handling</h3>
                    <div class="paragraph">
                        <p>As we`ve also seen in the <a href="#secure-objects">Technical Overview</a> chapter, Spring Security provides interceptors which control access to secure objects such as method invocations or web requests. A pre-invocation decision on whether the invocation is allowed to proceed is made by the <code>AccessDecisionManager</code>.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="authz-access-decision-manager"><a class="anchor" href="#authz-access-decision-manager"></a>1.2.1. The AccessDecisionManager</h4>
                        <div class="paragraph">
                            <p>The <code>AccessDecisionManager</code> is called by the <code>AbstractSecurityInterceptor</code> and is responsible for making final access control decisions. the <code>AccessDecisionManager</code> interface contains three methods:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>void decide(Authentication authentication, Object secureObject,
    Collection&lt;ConfigAttribute&gt; attrs) throws AccessDeniedException;

boolean supports(ConfigAttribute attribute);

boolean supports(Class clazz);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>AccessDecisionManager</code>'s <code>decide</code> method is passed all the relevant information it needs in order to make an authorization decision. In particular, passing the secure <code>Object</code> enables those arguments contained in the actual secure object invocation to be inspected. For example, let`s assume the secure object was a`MethodInvocation`. It would be easy to query the <code>MethodInvocation</code> for any <code>Customer</code> argument, and then implement some sort of security logic in the <code>AccessDecisionManager</code> to ensure the principal is permitted to operate on that customer. Implementations are expected to throw an <code>AccessDeniedException</code> if access is denied.</p>
                        </div>
                        <div class="paragraph">
                            <p>The <code>supports(ConfigAttribute)</code> method is called by the <code>AbstractSecurityInterceptor</code> at startup time to determine if the <code>AccessDecisionManager</code> can process the passed <code>ConfigAttribute</code>. The <code>supports(Class)</code> method is called by a security interceptor implementation to ensure the configured <code>AccessDecisionManager</code> supports the type of secure object that the security interceptor will present.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="authz-voting-based"><a class="anchor" href="#authz-voting-based"></a>1.2.2. Voting-Based AccessDecisionManager Implementations</h4>
                        <div class="paragraph">
                            <p>Whilst users can implement their own <code>AccessDecisionManager</code> to control all aspects of authorization, Spring Security includes several <code>AccessDecisionManager</code> implementations that are based on voting. <a href="#authz-access-voting">Voting Decision Manager</a> illustrates the relevant classes.</p>
                        </div>
                        <div id="authz-access-voting" class="imageblock">
                            <div class="content">
                                <img src="images/access-decision-voting.png" alt="access decision voting">
                            </div>
                            <div class="title">Figure 2. Voting Decision Manager</div>
                        </div>
                        <div class="paragraph">
                            <p>Using this approach, a series of <code>AccessDecisionVoter</code> implementations are polled on an authorization decision. The <code>AccessDecisionManager</code> then decides whether or not to throw an <code>AccessDeniedException</code> based on its assessment of the votes.</p>
                        </div>
                        <div class="paragraph">
                            <p>The <code>AccessDecisionVoter</code> interface has three methods:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>int vote(Authentication authentication, Object object, Collection&lt;ConfigAttribute&gt; attrs);

boolean supports(ConfigAttribute attribute);

boolean supports(Class clazz);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Concrete implementations return an <code>int</code>, with possible values being reflected in the <code>AccessDecisionVoter</code> static fields <code>ACCESS_ABSTAIN</code>, <code>ACCESS_DENIED</code> and <code>ACCESS_GRANTED</code>. A voting implementation will return <code>ACCESS_ABSTAIN</code> if it has no opinion on an authorization decision. If it does have an opinion, it must return either <code>ACCESS_DENIED</code> or <code>ACCESS_GRANTED</code>.</p>
                        </div>
                        <div class="paragraph">
                            <p>There are three concrete <code>AccessDecisionManager</code> s provided with Spring Security that tally the votes. the <code>ConsensusBased</code> implementation will grant or deny access based on the consensus of non-abstain votes. Properties are provided to control behavior in the event of an equality of votes or if all votes are abstain. The <code>AffirmativeBased</code> implementation will grant access if one or more <code>ACCESS_GRANTED</code> votes were received (i.e. a deny vote will be ignored, provided there was at least one grant vote). Like the <code>ConsensusBased</code> implementation, there is a parameter that controls the behavior if all voters abstain. The <code>UnanimousBased</code> provider expects unanimous <code>ACCESS_GRANTED</code> votes in order to grant access, ignoring abstains. It will deny access if there is any <code>ACCESS_DENIED</code> vote. Like the other implementations, there is a parameter that controls the behaviour if all voters abstain.</p>
                        </div>
                        <div class="paragraph">
                            <p>It is possible to implement a custom <code>AccessDecisionManager</code> that tallies votes differently. For example, votes from a particular <code>AccessDecisionVoter</code> might receive additional weighting, whilst a deny vote from a particular voter may have a veto effect.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="authz-role-voter"><a class="anchor" href="#authz-role-voter"></a>RoleVoter</h5>
                            <div class="paragraph">
                                <p>The most commonly used <code>AccessDecisionVoter</code> provided with Spring Security is the simple <code>RoleVoter</code>, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role.</p>
                            </div>
                            <div class="paragraph">
                                <p>It will vote if any <code>ConfigAttribute</code> begins with the prefix <code>ROLE_</code>. It will vote to grant access if there is a <code>GrantedAuthority</code> which returns a <code>String</code> representation (via the <code>getAuthority()</code> method) exactly equal to one or more <code>ConfigAttributes</code> starting with the prefix <code>ROLE_</code>. If there is no exact match of any <code>ConfigAttribute</code> starting with <code>ROLE_</code>, the <code>RoleVoter</code> will vote to deny access. If no <code>ConfigAttribute</code> begins with <code>ROLE_</code>, the voter will abstain.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="authz-authenticated-voter"><a class="anchor" href="#authz-authenticated-voter"></a>AuthenticatedVoter</h5>
                            <div class="paragraph">
                                <p>Another voter which we`ve implicitly seen is the <code>AuthenticatedVoter</code>, which can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access.</p>
                            </div>
                            <div class="paragraph">
                                <p>When we`ve used the attribute <code>IS_AUTHENTICATED_ANONYMOUSLY</code> to grant anonymous access, this attribute was being processed by the <code>AuthenticatedVoter</code>. See the Javadoc for this class for more information.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="authz-custom-voter"><a class="anchor" href="#authz-custom-voter"></a>Custom Voters</h5>
                            <div class="paragraph">
                                <p>Obviously, you can also implement a custom <code>AccessDecisionVoter</code> and you can put just about any access-control logic you want in it. It might be specific to your application (business-logic related) or it might implement some security administration logic. For example, you`ll find a <a href="http://blog.springsource.com/2009/01/02/spring-security-customization-part-2-adjusting-secured-session-in-real-time/"> blog article</a> on the SpringSource web site which describes how to use a voter to deny access in real-time to users whose accounts have been suspended.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="authz-after-invocation-handling"><a class="anchor" href="#authz-after-invocation-handling"></a>1.3. After Invocation Handling</h3>
                    <div class="paragraph">
                        <p>Whilst the <code>AccessDecisionManager</code> is called by the <code>AbstractSecurityInterceptor</code> before proceeding with the secure object invocation, some applications need a way of modifying the object actually returned by the secure object invocation. Whilst you could easily implement your own AOP concern to achieve this, Spring Security provides a convenient hook that has several concrete implementations that integrate with its ACL capabilities.</p>
                    </div>
                    <div class="paragraph">
                        <p><a href="#authz-after-invocation">After Invocation Implementation</a> illustrates Spring Security`s <code>AfterInvocationManager</code> and its concrete implementations.</p>
                    </div>
                    <div id="authz-after-invocation" class="imageblock">
                        <div class="content">
                            <img src="images/after-invocation.png" alt="after invocation">
                        </div>
                        <div class="title">Figure 3. After Invocation Implementation</div>
                    </div>
                    <div class="paragraph">
                        <p>Like many other parts of Spring Security, <code>AfterInvocationManager</code> has a single concrete implementation, <code>AfterInvocationProviderManager</code>, which polls a list of <code>AfterInvocationProvider</code> s. Each <code>AfterInvocationProvider</code> is allowed to modify the return object or throw an <code>AccessDeniedException</code>. Indeed multiple providers can modify the object, as the result of the previous provider is passed to the next in the list.</p>
                    </div>
                    <div class="paragraph">
                        <p>Please be aware that if you`re using <code>AfterInvocationManager</code>, you will still need configuration attributes that allow the <code>MethodSecurityInterceptor</code>'s <code>AccessDecisionManager</code> to allow an operation. If you`re using the typical Spring Security included <code>AccessDecisionManager</code> implementations, having no configuration attributes defined for a particular secure method invocation will cause each <code>AccessDecisionVoter</code> to abstain from voting. In turn, if the <code>AccessDecisionManager</code> property "<code>allowIfAllAbstainDecisions</code>" is <code>false</code>, an <code>AccessDeniedException</code> will be thrown. You may avoid this potential issue by either (i) setting "<code>allowIfAllAbstainDecisions</code>" to <code>true</code> (although this is generally not recommended) or (ii) simply ensure that there is at least one configuration attribute that an <code>AccessDecisionVoter</code> will vote to grant access for. This latter (recommended) approach is usually achieved through a <code>ROLE_USER</code> or <code>ROLE_AUTHENTICATED</code> configuration attribute.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="authz-hierarchical-roles"><a class="anchor" href="#authz-hierarchical-roles"></a>1.4. Hierarchical Roles</h3>
                    <div class="paragraph">
                        <p>It is a common requirement that a particular role in an application should automatically "include" other roles. For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. To achieve this, you can either make sure that all admin users are also assigned the "user" role. Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. This can get quite complicated if you have a lot of different roles in your application.</p>
                    </div>
                    <div class="paragraph">
                        <p>The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. An extended version of Spring Security`s <a href="#authz-role-voter">RoleVoter</a>, <code>RoleHierarchyVoter</code>, is configured with a <code>RoleHierarchy</code>, from which it obtains all the "reachable authorities" which the user is assigned. A typical configuration might look like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter"&gt;
    &lt;constructor-arg ref="roleHierarchy" /&gt;
&lt;/bean&gt;
&lt;bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl"&gt;
    &lt;property name="hierarchy"&gt;
        &lt;value&gt;
            ROLE_ADMIN &gt; ROLE_STAFF
            ROLE_STAFF &gt; ROLE_USER
            ROLE_USER &gt; ROLE_GUEST
        &lt;/value&gt;
    &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Here we have four roles in a hierarchy <code>ROLE_ADMIN =&gt; ROLE_STAFF =&gt; ROLE_USER =&gt; ROLE_GUEST</code>. A user who is authenticated with <code>ROLE_ADMIN</code>, will behave as if they have all four roles when security contraints are evaluated against an <code>AccessDecisionManager</code> cconfigured with the above <code>RoleHierarchyVoter</code>. The <code>&gt;</code> symbol can be thought of as meaning "includes".</p>
                    </div>
                    <div class="paragraph">
                        <p>Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="secure-object-impls"><a class="anchor" href="#secure-object-impls"></a>2. Secure Object Implementations</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="aop-alliance"><a class="anchor" href="#aop-alliance"></a>2.1. AOP Alliance (MethodInvocation) Security Interceptor</h3>
                    <div class="paragraph">
                        <p>Prior to Spring Security 2.0, securing <code>MethodInvocation</code> s needed quite a lot of boiler plate configuration. Now the recommended approach for method security is to use <a href="#ns-method-security">namespace configuration</a>. This way the method security infrastructure beans are configured automatically for you so you don`t really need to know about the implementation classes. We`ll just provide a quick overview of the classes that are involved here.</p>
                    </div>
                    <div class="paragraph">
                        <p>Method security in enforced using a <code>MethodSecurityInterceptor</code>, which secures <code>MethodInvocation</code> s. Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. The interceptor uses a <code>MethodSecurityMetadataSource</code> instance to obtain the configuration attributes that apply to a particular method invocation. <code>MapBasedMethodSecurityMetadataSource</code> is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the <code>&lt;intercept-methods&gt;</code> or <code>&lt;protect-point&gt;</code> elements. Other implementations will be used to handle annotation-based configuration.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="explicit-methodsecurityinterceptor-configuration"><a class="anchor" href="#explicit-methodsecurityinterceptor-configuration"></a>2.1.1. Explicit MethodSecurityInterceptor Configuration</h4>
                        <div class="paragraph">
                            <p>You can of course configure a <code>MethodSecurityIterceptor</code> directly in your application context for use with one of Spring AOP`s proxying mechanisms:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="bankManagerSecurity" class=
    "org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="accessDecisionManager" ref="accessDecisionManager"/&gt;
  &lt;property name="afterInvocationManager" ref="afterInvocationManager"/&gt;
  &lt;property name="securityMetadataSource"&gt;
    &lt;sec:method-security-metadata-source&gt;
      &lt;sec:protect method="com.mycompany.BankManager.delete*" access="ROLE_SUPERVISOR"/&gt;
      &lt;sec:protect method="com.mycompany.BankManager.getBalance" access="ROLE_TELLER,ROLE_SUPERVISOR"/&gt;
    &lt;/sec:method-security-metadata-source&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="aspectj"><a class="anchor" href="#aspectj"></a>2.2. AspectJ (JoinPoint) Security Interceptor</h3>
                    <div class="paragraph">
                        <p>The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. Indeed we will only discuss the differences in this section.</p>
                    </div>
                    <div class="paragraph">
                        <p>The AspectJ interceptor is named <code>AspectJSecurityInterceptor</code>. Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor via proxying, the <code>AspectJSecurityInterceptor</code> is weaved in via the AspectJ compiler. It would not be uncommon to use both types of security interceptors in the same application, with <code>AspectJSecurityInterceptor</code> being used for domain object instance security and the AOP Alliance <code>MethodSecurityInterceptor</code> being used for services layer security.</p>
                    </div>
                    <div class="paragraph">
                        <p>Let`s first consider how the <code>AspectJSecurityInterceptor</code> is configured in the Spring application context:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="bankManagerSecurity" class=
    "org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
  &lt;property name="accessDecisionManager" ref="accessDecisionManager"/&gt;
  &lt;property name="afterInvocationManager" ref="afterInvocationManager"/&gt;
  &lt;property name="securityMetadataSource"&gt;
    &lt;sec:method-security-metadata-source&gt;
      &lt;sec:protect method="com.mycompany.BankManager.delete*" access="ROLE_SUPERVISOR"/&gt;
      &lt;sec:protect method="com.mycompany.BankManager.getBalance" access="ROLE_TELLER,ROLE_SUPERVISOR"/&gt;
    &lt;/sec:method-security-metadata-source&gt;
&lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>As you can see, aside from the class name, the <code>AspectJSecurityInterceptor</code> is exactly the same as the AOP Alliance security interceptor. Indeed the two interceptors can share the same`securityMetadataSource`, as the <code>SecurityMetadataSource</code> works with <code>java.lang.reflect.Method</code> s rather than an AOP library-specific class. Of course, your access decisions have access to the relevant AOP library-specific invocation (ie <code>MethodInvocation</code> or <code>JoinPoint</code>) and as such can consider a range of addition criteria when making access decisions (such as method arguments).</p>
                    </div>
                    <div class="paragraph">
                        <p>Next you`ll need to define an AspectJ <code>aspect</code>. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>
package org.springframework.security.samples.aspectj;

import org.springframework.security.access.intercept.aspectj.AspectJSecurityInterceptor;
import org.springframework.security.access.intercept.aspectj.AspectJCallback;
import org.springframework.beans.factory.InitializingBean;

public aspect DomainObjectInstanceSecurityAspect implements InitializingBean {

    private AspectJSecurityInterceptor securityInterceptor;

    pointcut domainObjectInstanceExecution(): target(PersistableEntity)
        &amp;&amp; execution(public * *(..)) &amp;&amp; !within(DomainObjectInstanceSecurityAspect);

    Object around(): domainObjectInstanceExecution() {
        if (this.securityInterceptor == null) {
            return proceed();
        }

        AspectJCallback callback = new AspectJCallback() {
            public Object proceedWithObject() {
                return proceed();
            }
        };

        return this.securityInterceptor.invoke(thisJoinPoint, callback);
    }

    public AspectJSecurityInterceptor getSecurityInterceptor() {
        return securityInterceptor;
    }

    public void setSecurityInterceptor(AspectJSecurityInterceptor securityInterceptor) {
        this.securityInterceptor = securityInterceptor;
    }

    public void afterPropertiesSet() throws Exception {
        if (this.securityInterceptor == null)
            throw new IllegalArgumentException("securityInterceptor required");
        }
    }
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>In the above example, the security interceptor will be applied to every instance of <code>PersistableEntity</code>, which is an abstract class not shown (you can use any other class or <code>pointcut</code> expression you like). For those curious, <code>AspectJCallback</code> is needed because the <code>proceed();</code> statement has special meaning only within an <code>around()</code> body. The <code>AspectJSecurityInterceptor</code> calls this anonymous <code>AspectJCallback</code> class when it wants the target object to continue.</p>
                    </div>
                    <div class="paragraph">
                        <p>You will need to configure Spring to load the aspect and wire it with the <code>AspectJSecurityInterceptor</code>. A bean declaration which achieves this is shown below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="domainObjectInstanceSecurityAspect"
     class="security.samples.aspectj.DomainObjectInstanceSecurityAspect"
     factory-method="aspectOf"&gt;
  &lt;property name="securityInterceptor" ref="bankManagerSecurity"/&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>That`s it! Now you can create your beans from anywhere within your application, using whatever means you think fit (eg <code>new Person();</code>) and they will have the security interceptor applied.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="el-access"><a class="anchor" href="#el-access"></a>3. Expression-Based Access Control</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have seen before. Expression-based access control is built on the same architecture but allows complicated boolean logic to be encapsulated in a single expression.</p>
                </div>
                <div class="sect2">
                    <h3 id="overview"><a class="anchor" href="#overview"></a>3.1. Overview</h3>
                    <div class="paragraph">
                        <p>Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. Expressions are evaluated with a "root object" as part of the evaluation context. Spring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="el-common-built-in"><a class="anchor" href="#el-common-built-in"></a>3.1.1. Common Built-In Expressions</h4>
                        <div class="paragraph">
                            <p>The base class for expression root objects is <code>SecurityExpressionRoot</code>. This provides some common expressions which are available in both web and method security.</p>
                        </div>
                        <table id="common-expressions" class="tableblock frame-all grid-all" style="width:100%; ">
                            <caption class="title">Table 2. Common built-in expressions</caption>
                            <colgroup>
                                <col style="width:50%;">
                                <col style="width:50%;">
                            </colgroup>
                            <thead>
                                <tr>
                                    <th class="tableblock halign-left valign-top">Expression</th>
                                    <th class="tableblock halign-left valign-top">Description</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasRole([role])</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal has the specified role. This is a synonym for <code>hasAuthority([authority])</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasAnyRole([role1,role2])</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal has any of the supplied roles (given as a comma-separated list of strings) This is a synonym for <code>hasAnyAuthority([authority1,authority2])</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasAuthority([authority])</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal has the specified authority. This is a synonym for <code>hasRole([role])</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasAnyAuthority([authority1,authority2])</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal has any of the supplied roles (given as a comma-separated list of strings) <code>hasAnyRole([role1,role2])``hasAnyRole([role1,role2])</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>principal</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Allows direct access to the principal object representing the current user</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>authentication</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Allows direct access to the current <code>Authentication</code> object obtained from the <code>SecurityContext</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>permitAll</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Always evaluates to <code>true</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>denyAll</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Always evaluates to <code>false</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>isAnonymous()</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal is an anonymous user</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>isRememberMe()</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the current principal is a remember-me user</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>isAuthenticated()</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the user is not anonymous</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>isFullyAuthenticated()</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the user is not an anonymous or a remember-me user</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasPermission(Object target, Object permission)</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the user has access to the provided target for the given permission. For example, <code>hasPermission(domainObject, 'read')</code></p>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock"><code>hasPermission(Object targetId, String targetType, Object permission)</code></p>
                                    </td>
                                    <td class="tableblock halign-left valign-top">
                                        <p class="tableblock">Returns <code>true</code> if the user has access to the provided target for the given permission. For example, <code>hasPermission(1, 'com.example.domain.Message', 'read')</code></p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="el-access-web"><a class="anchor" href="#el-access-web"></a>3.2. Web Security Expressions</h3>
                    <div class="paragraph">
                        <p>To use expressions to secure individual URLs, you would first need to set the <code>use-expressions</code> attribute in the <code>&lt;http&gt;</code> element to <code>true</code>. Spring Security will then expect the <code>access</code> attributes of the <code>&lt;intercept-url&gt;</code> elements to contain Spring EL expressions. The expressions should evaluate to a boolean, defining whether access should be allowed or not. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
  &lt;http use-expressions="true"&gt;
    &lt;intercept-url pattern="/admin*"
        access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/&gt;
    ...
  &lt;/http&gt;
</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet. We`ve already seen the built-in <code>hasRole</code> expression in the previous section. The expression <code>hasIpAddress</code> is an additional built-in expression which is specific to web security. It is defined by the <code>WebSecurityExpressionRoot</code> class, an instance of which is used as the expression root object when evaluation web-access expressions. This object also directly exposed the <code>HttpServletRequest</code> object under the name <code>request</code> so you can invoke the request directly in an expressio If expressions are being used, a <code>WebExpressionVoter</code> will be added to the <code>AccessDecisionManager</code> which is used by the namespace. So if you aren`t using the namespace and want to use expressions, you will have to add one of these to your configuration.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="method-security-expressions"><a class="anchor" href="#method-security-expressions"></a>3.3. Method Security Expressions</h3>
                    <div class="paragraph">
                        <p>Method security is a bit more complicated than a simple allow or deny rule. Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="el-pre-post-annotations"><a class="anchor" href="#el-pre-post-annotations"></a>3.3.1. @Pre and @Post Annotations</h4>
                        <div class="paragraph">
                            <p>There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. They are <code>@PreAuthorize</code>, <code>@PreFilter</code>, <code>@PostAuthorize</code> and <code>@PostFilter</code>. Their use is enabled through the <code>global-method-security</code> namespace element:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;global-method-security pre-post-annotations="enabled"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="access-control-using-preauthorize-and-postauthorize"><a class="anchor" href="#access-control-using-preauthorize-and-postauthorize"></a>Access Control using @PreAuthorize and @PostAuthorize</h5>
                            <div class="paragraph">
                                <p>The most obviously useful annotation is <code>@PreAuthorize</code> which decides whether a method can actually be invoked or not. For example (from the"Contacts" sample application)</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>which means that access will only be allowed for users with the role "ROLE_USER". Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. But what about:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>@PreAuthorize("hasPermission(#contact, 'admin')")
public void deletePermission(Contact contact, Sid recipient, Permission permission);</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>Here we`re actually using a method argument as part of the expression to decide whether the current user has the "admin"permission for the given contact. The built-in <code>hasPermission()</code> expression is linked into the Spring Security ACL module through the application context, as we`ll<a href="#el-permission-evaluator">see below</a>. You can access any of the method arguments by name as expression variables.</p>
                            </div>
                            <div class="paragraph">
                                <p>There are a number of ways in which Spring Security can resolve the method arguments. Spring Security uses <code>DefaultSecurityParameterNameDiscoverer</code> to discover the parameter names. By default, the following options are tried for a method as a whole.</p>
                            </div>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p>If Spring Security`s <code>@P</code> annotation is present on a single argument to the method, the value will be used. This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. For example:</p>
                                        <div class="listingblock">
                                            <div class="content">
                                                <pre class="prettyprint java language-java"><code>import org.springframework.security.access.method.P;

...

@PreAuthorize("#c.name == authentication.name")
public void doSomething(@P("c") Contact contact);</code></pre>
                                            </div>
                                        </div>
                                        <div class="paragraph">
                                            <p>Behind the scenes this use implemented using <code>AnnotationParameterNameDiscoverer</code> which can be customized to support the value attribute of any specified annotation.</p>
                                        </div>
                                    </li>
                                    <li>
                                        <p>If Spring Data`s <code>@Param</code> annotation is present on at least one parameter for the method, the value will be used. This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. For example:</p>
                                        <div class="listingblock">
                                            <div class="content">
                                                <pre class="prettyprint java language-java"><code>import org.springframework.data.repository.query.Param;

...

@PreAuthorize("#n == authentication.name")
Contact findContactByName(@Param("n") String name);</code></pre>
                                            </div>
                                        </div>
                                        <div class="paragraph">
                                            <p>Behind the scenes this use implemented using <code>AnnotationParameterNameDiscoverer</code> which can be customized to support the value attribute of any specified annotation.</p>
                                        </div>
                                    </li>
                                    <li>
                                        <p>If JDK 8 was used to compile the source with the -parameters argument and Spring 4+ is being used, then the standard JDK reflection API is used to discover the parameter names. This works on both classes and interfaces.</p>
                                    </li>
                                    <li>
                                        <p>Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols. This will not work for interfaces since they do not have debug information about the parameter names. For interfaces, annotations or the JDK 8 approach must be used.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="openblock">
                                <div class="title">
                                    <a id="el-pre-post-annotations-spel"></a>
                                </div>
                                <div class="content">
                                    <div class="paragraph">
                                        <p>Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments. For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write</p>
                                    </div>
                                </div>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>@PreAuthorize("#contact.name == authentication.name")
public void doSomething(Contact contact);</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>Here we are accessing another built-in expression, <code>authentication</code>, which is the <code>Authentication</code> stored in the security context. You can also access its "principal" property directly, using the expression <code>principal</code>. The value will often be a <code>UserDetails</code> instance, so you might use an expression like <code>principal.username</code> or <code>principal.enabled</code>.</p>
                            </div>
                            <div class="openblock">
                                <div class="title">
                                    <a id="el-pre-post-annotations-post"></a>
                                </div>
                                <div class="content">
                                    <div class="paragraph">
                                        <p>Less commonly, you may wish to perform an access-control check after the method has been invoked. This can be achieved using the <code>@PostAuthorize</code> annotation. To access the return value from a method, use the built-in name <code>returnObject</code> in the expression.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="filtering-using-prefilter-and-postfilter"><a class="anchor" href="#filtering-using-prefilter-and-postfilter"></a>Filtering using @PreFilter and @PostFilter</h5>
                            <div class="paragraph">
                                <p>As you may already be aware, Spring Security supports filtering of collections and arrays and this can now be achieved using expressions. This is most commonly performed on the return value of a method. For example:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>@PreAuthorize("hasRole('ROLE_USER')")
@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
public List&lt;Contact&gt; getAll();</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>When using the <code>@PostFilter</code> annotation, Spring Security iterates through the returned collection and removes any elements for which the supplied expression is false. The name <code>filterObject</code> refers to the current object in the collection. You can also filter before the method call, using <code>@PreFilter</code>, though this is a less common requirement. The syntax is just the same, but if there is more than one argument which is a collection type then you have to select one by name using the <code>filterTarget</code> property of this annotation.</p>
                            </div>
                            <div class="paragraph">
                                <p>Note that filtering is obviously not a substitute for tuning your data retrieval queries. If you are filtering large collections and removing many of the entries then this is likely to be inefficient.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="el-method-built-in"><a class="anchor" href="#el-method-built-in"></a>3.3.2. Built-In Expressions</h4>
                        <div class="paragraph">
                            <p>There are some built-in expressions which are specific to method security, which we have already seen in use above. The <code>filterTarget</code> and <code>returnValue</code> values are simple enough, but the use of the <code>hasPermission()</code> expression warrants a closer look.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="el-permission-evaluator"><a class="anchor" href="#el-permission-evaluator"></a>The PermissionEvaluator interface</h5>
                            <div class="paragraph">
                                <p><code>hasPermission()</code> expressions are delegated to an instance of <code>PermissionEvaluator</code>. It is intended to bridge between the expression system and Spring Security`s ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. The interface has two methods:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>boolean hasPermission(Authentication authentication, Object targetDomainObject,
                             Object permission);

boolean hasPermission(Authentication authentication, Serializable targetId,
                              String targetType, Object permission);</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>which map directly to the available versions of the expression, with the exception that the first argument (the <code>Authentication</code> object) is not supplied. The first is used in situations where the domain object, to which access is being controlled, is already loaded. Then expression will return true if the current user has the given permission for that object. The second version is used in cases where the object is not loaded, but its identifier is known. An abstract "type" specifier for the domain object is also required, allowing the correct ACL permissions to be loaded. This has traditionally been the Java class of the object, but does not have to be as long as it is consistent with how the permissions are loaded.</p>
                            </div>
                            <div class="paragraph">
                                <p>To use <code>hasPermission()</code> expressions, you have to explicitly configure a <code>PermissionEvaluator</code> in your application context. This would look something like this:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;security:global-method-security pre-post-annotations="enabled"&gt;
  &lt;security:expression-handler ref="expressionHandler"/&gt;
&lt;/security:global-method-security&gt;

&lt;bean id="expressionHandler" class=
  "org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"&gt;
     &lt;property name="permissionEvaluator" ref="myPermissionEvaluator"/&gt;
&lt;/bean&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>Where <code>myPermissionEvaluator</code> is the bean which implements <code>PermissionEvaluator</code>. Usually this will be the implementation from the ACL module which is called`AclPermissionEvaluator`. See the "Contacts" sample application configuration for more details.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <h1 id="advanced-topics" class="sect0"><a class="anchor" href="#advanced-topics"></a>Additional Topics</h1>
        <div class="paragraph">
            <p>In this part we cover features which require a knowledge of previous chapters as well as some of the more advanced and less-commonly used features of the framework.</p>
        </div>
        <div class="sect1">
            <h2 id="domain-acls"><a class="anchor" href="#domain-acls"></a>1. Domain Object Security (ACLs)</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="domain-acls-overview"><a class="anchor" href="#domain-acls-overview"></a>1.1. Overview</h3>
                    <div class="paragraph">
                        <p>Complex applications often will find the need to define access permissions not simply at a web request or method invocation level. Instead, security decisions need to comprise both who (<code>Authentication</code>), where (<code>MethodInvocation</code>) and what (<code>SomeDomainObject</code>). In other words, authorization decisions also need to consider the actual domain object instance subject of a method invocation.</p>
                    </div>
                    <div class="paragraph">
                        <p>Imagine you`re designing an application for a pet clinic. There will be two main groups of users of your Spring-based application: staff of the pet clinic, as well as the pet clinic`s customers. The staff will have access to all of the data, whilst your customers will only be able to see their own customer records. To make it a little more interesting, your customers can allow other users to see their customer records, such as their "puppy preschool" mentor or president of their local "Pony Club". Using Spring Security as the foundation, you have several approaches that can be used:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>Write your business methods to enforce the security. You could consult a collection within the <code>Customer</code> domain object instance to determine which users have access. By using the <code>SecurityContextHolder.getContext().getAuthentication()</code>, you`ll be able to access the <code>Authentication</code> object.</p>
                            </li>
                            <li>
                                <p>Write an <code>AccessDecisionVoter</code> to enforce the security from the <code>GrantedAuthority[]</code> s stored in the <code>Authentication</code> object. This would mean your <code>AuthenticationManager</code> would need to populate the <code>Authentication</code> with custom <code>GrantedAuthority</code>[]s representing each of the <code>Customer</code> domain object instances the principal has access to.</p>
                            </li>
                            <li>
                                <p>Write an <code>AccessDecisionVoter</code> to enforce the security and open the target <code>Customer</code> domain object directly. This would mean your voter needs access to a DAO that allows it to retrieve the <code>Customer</code> object. It would then access the <code>Customer</code> object`s collection of approved users and make the appropriate decision.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>Each one of these approaches is perfectly legitimate. However, the first couples your authorization checking to your business code. The main problems with this include the enhanced difficulty of unit testing and the fact it would be more difficult to reuse the <code>Customer</code> authorization logic elsewhere. Obtaining the <code>GrantedAuthority[]</code> s from the <code>Authentication</code> object is also fine, but will not scale to large numbers of <code>Customer</code> s. If a user might be able to access 5,000 <code>Customer</code> s (unlikely in this case, but imagine if it were a popular vet for a large Pony Club!) the amount of memory consumed and time required to construct the <code>Authentication</code> object would be undesirable. The final method, opening the <code>Customer</code> directly from external code, is probably the best of the three. It achieves separation of concerns, and doesn`t misuse memory or CPU cycles, but it is still inefficient in that both the <code>AccessDecisionVoter</code> and the eventual business method itself will perform a call to the DAO responsible for retrieving the <code>Customer</code> object. Two accesses per method invocation is clearly undesirable. In addition, with every approach listed you`ll need to write your own access control list (ACL) persistence and business logic from scratch.</p>
                    </div>
                    <div class="paragraph">
                        <p>Fortunately, there is another alternative, which we`ll talk about below.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="domain-acls-key-concepts"><a class="anchor" href="#domain-acls-key-concepts"></a>1.2. Key Concepts</h3>
                    <div class="paragraph">
                        <p>Spring Security`s ACL services are shipped in the <code>spring-security-acl-xxx.jar</code>. You will need to add this JAR to your classpath to use Spring Security`s domain object instance security capabilities.</p>
                    </div>
                    <div class="paragraph">
                        <p>Spring Security`s domain object instance security capabilities centre on the concept of an access control list (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of who can and can`t work with that domain object. With this in mind, Spring Security delivers three main ACL-related capabilities to your application:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those ACLs)</p>
                            </li>
                            <li>
                                <p>A way of ensuring a given principal is permitted to work with your objects, before methods are called</p>
                            </li>
                            <li>
                                <p>A way of ensuring a given principal is permitted to work with your objects (or something they return), after methods are called</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>As indicated by the first bullet point, one of the main capabilities of the Spring Security ACL module is providing a high-performance way of retrieving ACLs. This ACL repository capability is extremely important, because every domain object instance in your system might have several access control entries, and each ACL might inherit from other ACLs in a tree-like structure (this is supported out-of-the-box by Spring Security, and is very commonly used). Spring Security`s ACL capability has been carefully designed to provide high performance retrieval of ACLs, together with pluggable caching, deadlock-minimizing database updates, independence from ORM frameworks (we use JDBC directly), proper encapsulation, and transparent database updating.</p>
                    </div>
                    <div class="paragraph">
                        <p>Given databases are central to the operation of the ACL module, let`s explore the four main tables used by default in the implementation. The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a <code>GrantedAuthority</code>. Thus, there is a single row for each unique principal or <code>GrantedAuthority</code>. When used in the context of receiving a permission, a SID is generally called a "recipient".</p>
                            </li>
                            <li>
                                <p>ACL_CLASS allows us to uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. Thus, there is a single row for each unique Class we wish to store ACL permissions for.</p>
                            </li>
                            <li>
                                <p>ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we`re providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. We have a single row for every domain object instance we`re storing ACL permissions for.</p>
                            </li>
                            <li>
                                <p>Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (ie a foreign key to ACL_SID), whether we`ll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. We have a single row for every recipient that receives a permission to work with a domain object.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>As mentioned in the last paragraph, the ACL system uses integer bit masking. Don`t worry, you need not be aware of the finer points of bit shifting to use the ACL system, but suffice to say that we have 32 bits we can switch on or off. Each of these bits represents a permission, and by default the permissions are read (bit 0), write (bit 1), create (bit 2), delete (bit 3) and administer (bit 4). It`s easy to implement your own <code>Permission</code> instance if you wish to use other permissions, and the remainder of the ACL framework will operate without knowledge of your extensions.</p>
                    </div>
                    <div class="paragraph">
                        <p>It is important to understand that the number of domain objects in your system has absolutely no bearing on the fact we`ve chosen to use integer bit masking. Whilst you have 32 bits available for permissions, you could have billions of domain object instances (which will mean billions of rows in ACL_OBJECT_IDENTITY and quite probably ACL_ENTRY). We make this point because we`ve found sometimes people mistakenly believe they need a bit for each potential domain object, which is not the case.</p>
                    </div>
                    <div class="paragraph">
                        <p>Now that we`ve provided a basic overview of what the ACL system does, and what it looks like at a table structure, let`s explore the key interfaces. The key interfaces are:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p><code>Acl</code>: Every domain object has one and only one <code>Acl</code> object, which internally holds the <code>AccessControlEntry</code> s as well as knows the owner of the <code>Acl</code>. An Acl does not refer directly to the domain object, but instead to an <code>ObjectIdentity</code>. The <code>Acl</code> is stored in the ACL_OBJECT_IDENTITY table.</p>
                            </li>
                            <li>
                                <p><code>AccessControlEntry</code>: An <code>Acl</code> holds multiple <code>AccessControlEntry</code> s, which are often abbreviated as ACEs in the framework. Each ACE refers to a specific tuple of`Permission`, <code>Sid</code> and <code>Acl</code>. An ACE can also be granting or non-granting and contain audit settings. The ACE is stored in the ACL_ENTRY table.</p>
                            </li>
                            <li>
                                <p><code>Permission</code>: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the <code>BasePermission</code> class.</p>
                            </li>
                            <li>
                                <p><code>Sid</code>: The ACL module needs to refer to principals and <code>GrantedAuthority[]</code> s. A level of indirection is provided by the <code>Sid</code> interface, which is an abbreviation of "security identity". Common classes include <code>PrincipalSid</code> (to represent the principal inside an <code>Authentication</code> object) and <code>GrantedAuthoritySid</code>. The security identity information is stored in the ACL_SID table.</p>
                            </li>
                            <li>
                                <p><code>ObjectIdentity</code>: Each domain object is represented internally within the ACL module by an <code>ObjectIdentity</code>. The default implementation is called <code>ObjectIdentityImpl</code>.</p>
                            </li>
                            <li>
                                <p><code>AclService</code>: Retrieves the <code>Acl</code> applicable for a given <code>ObjectIdentity</code>. In the included implementation (<code>JdbcAclService</code>), retrieval operations are delegated to a <code>LookupStrategy</code>. The <code>LookupStrategy</code> provides a highly optimized strategy for retrieving ACL information, using batched retrievals <code>(BasicLookupStrategy</code>) and supporting custom implementations that leverage materialized views, hierarchical queries and similar performance-centric, non-ANSI SQL capabilities.</p>
                            </li>
                            <li>
                                <p><code>MutableAclService</code>: Allows a modified <code>Acl</code> to be presented for persistence. It is not essential to use this interface if you do not wish.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>Please note that our out-of-the-box AclService and related database classes all use ANSI SQL. This should therefore work with all major databases. At the time of writing, the system had been successfully tested using Hypersonic SQL, PostgreSQL, Microsoft SQL Server and Oracle.</p>
                    </div>
                    <div class="paragraph">
                        <p>Two samples ship with Spring Security that demonstrate the ACL module. The first is the Contacts Sample, and the other is the Document Management System (DMS) Sample. We suggest taking a look over these for examples.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="domain-acls-getting-started"><a class="anchor" href="#domain-acls-getting-started"></a>1.3. Getting Started</h3>
                    <div class="paragraph">
                        <p>To get starting using Spring Security`s ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a <code>DataSource</code> using Spring. The <code>DataSource</code> is then injected into a <code>JdbcMutableAclService</code> and <code>BasicLookupStrategy</code> instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You`ll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements).</p>
                    </div>
                    <div class="paragraph">
                        <p>Once you`ve created the required schema and instantiated <code>JdbcMutableAclService</code>, you`ll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully <code>ObjectIdentityImpl</code> will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a <code>public Serializable getId()</code> method. If the return type is long, or compatible with long (eg an int), you will find you need not give further consideration to <code>ObjectIdentity</code> issues. Many parts of the ACL module rely on long identifiers. If you`re not using long (or an int, byte etc), there is a very good chance you`ll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security`s ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios.</p>
                    </div>
                    <div class="paragraph">
                        <p>The following fragment of code shows how to create an <code>Acl</code>, or modify an existing`Acl`:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>// Prepare the information we'd like in our access control entry (ACE)
ObjectIdentity oi = new ObjectIdentityImpl(Foo.class, new Long(44));
Sid sid = new PrincipalSid("Samantha");
Permission p = BasePermission.ADMINISTRATION;

// Create or update the relevant ACL
MutableAcl acl = null;
try {
  acl = (MutableAcl) aclService.readAclById(oi);
} catch (NotFoundException nfe) {
  acl = aclService.createAcl(oi);
}

// Now grant some permissions via an access control entry (ACE)
acl.insertAce(acl.getEntries().length, p, sid, true);
aclService.updateAcl(acl);</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>In the example above, we`re retrieving the ACL associated with the "Foo" domain object with identifier number 44. We`re then adding an ACE so that a principal named "Samantha" can "administer" the object. The code fragment is relatively self-explanatory, except the insertAce method. The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. In the example above, we`re just putting the new ACE at the end of the existing ACEs. The final argument is a boolean indicating whether the ACE is granting or denying. Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked.</p>
                    </div>
                    <div class="paragraph">
                        <p>Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. Instead, you will need to write code like shown above for your individual domain objects. It`s worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. We`ve found this quite an effective approach in the past.</p>
                    </div>
                    <div class="paragraph">
                        <p>Once you`ve used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. You could write your own <code>AccessDecisionVoter</code> or <code>AfterInvocationProvider</code> that respectively fires before or after a method invocation. Such classes would use <code>AclService</code> to retrieve the relevant ACL and then call <code>Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)</code> to decide whether permission is granted or denied. Alternately, you could use our <code>AclEntryVoter</code>, <code>AclEntryAfterInvocationProvider</code> or <code>AclEntryAfterInvocationCollectionFilteringProvider</code> classes. All of these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. Please refer to the sample applications to learn how to use these classes.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="preauth"><a class="anchor" href="#preauth"></a>2. Pre-Authentication Scenarios</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>There are situations where you want to use Spring Security for authorization, but the user has already been reliably authenticated by some external system prior to accessing the application. We refer to these situations as "pre-authenticated" scenarios. Examples include X.509, Siteminder and authentication by the Java EE container in which the application is running. When using pre-authentication, Spring Security has to</p>
                </div>
                <div class="ulist">
                    <ul>
                        <li>
                            <p>Identify the user making the request.</p>
                        </li>
                        <li>
                            <p>Obtain the authorities for the user.</p>
                        </li>
                    </ul>
                </div>
                <div class="paragraph">
                    <p>The details will depend on the external authentication mechanism. A user might be identified by their certificate information in the case of X.509, or by an HTTP request header in the case of Siteminder. If relying on container authentication, the user will be identified by calling the <code>getUserPrincipal()</code> method on the incoming HTTP request. In some cases, the external mechanism may supply role/authority information for the user but in others the authorities must be obtained from a separate source, such as a <code>UserDetailsService</code>.</p>
                </div>
                <div class="sect2">
                    <h3 id="pre-authentication-framework-classes"><a class="anchor" href="#pre-authentication-framework-classes"></a>2.1. Pre-Authentication Framework Classes</h3>
                    <div class="paragraph">
                        <p>Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes which provide an internal framework for implementing pre-authenticated authentication providers. This removes duplication and allows new implementations to be added in a structured fashion, without having to write everything from scratch. You don`t need to know about these classes if you want to use something like <a href="#x509">X.509 authentication</a>, as it already has a namespace configuration option which is simpler to use and get started with. If you need to use explicit bean configuration or are planning on writing your own implementation then an understanding of how the provided implementations work will be useful. You will find classes under the <code>org.springframework.security.web.authentication.preauth</code>. We just provide an outline here so you should consult the Javadoc and source where appropriate.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="abstractpreauthenticatedprocessingfilter"><a class="anchor" href="#abstractpreauthenticatedprocessingfilter"></a>2.1.1. AbstractPreAuthenticatedProcessingFilter</h4>
                        <div class="paragraph">
                            <p>This class will check the current contents of the security context and, if empty, it will attempt to extract user information from the HTTP request and submit it to the <code>AuthenticationManager</code>. Subclasses override the following methods to obtain this information:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>protected abstract Object getPreAuthenticatedPrincipal(HttpServletRequest request);

protected abstract Object getPreAuthenticatedCredentials(HttpServletRequest request);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>After calling these, the filter will create a <code>PreAuthenticatedAuthenticationToken</code> containing the returned data and submit it for authentication. By "authentication" here, we really just mean further processing to perhaps load the user`s authorities, but the standard Spring Security authentication architecture is followed.</p>
                        </div>
                        <div class="paragraph">
                            <p>Like other Spring Security authentication filters, the pre-authentication filter has an <code>authenticationDetailsSource</code> property which by default will create a <code>WebAuthenticationDetails</code> object to store additional information such as the session-identifier and originating IP address in the <code>details</code> property of the <code>Authentication</code> object. In cases where user role information can be obtained from the pre-authentication mechanism, the data is also stored in this property, with the details implementing the <code>GrantedAuthoritiesContainer</code> interface. This enables the authentication provider to read the authorities which were externally allocated to the user. We`ll look at a concrete example next.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="j2ee-preauth-details"><a class="anchor" href="#j2ee-preauth-details"></a>J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource</h5>
                            <div class="paragraph">
                                <p>If the filter is configured with an <code>authenticationDetailsSource</code> which is an instance of this class, the authority information is obtained by calling the <code>isUserInRole(String role)</code> method for each of a pre-determined set of "mappable roles". The class gets these from a configured <code>MappableAttributesRetriever</code>. Possible implementations include hard-coding a list in the application context and reading the role information from the <code>&lt;security-role&gt;</code> information in a <code>web.xml</code> file. The pre-authentication sample application uses the latter approach.</p>
                            </div>
                            <div class="paragraph">
                                <p>There is an additional stage where the roles (or attributes) are mapped to Spring Security <code>GrantedAuthority</code> objects using a configured <code>Attributes2GrantedAuthoritiesMapper</code>. The default will just add the usual <code>ROLE_</code> prefix to the names, but it gives you full control over the behaviour.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="preauthenticatedauthenticationprovider"><a class="anchor" href="#preauthenticatedauthenticationprovider"></a>2.1.2. PreAuthenticatedAuthenticationProvider</h4>
                        <div class="paragraph">
                            <p>The pre-authenticated provider has little more to do than load the <code>UserDetails</code> object for the user. It does this by delegating to a <code>AuthenticationUserDetailsService</code>. The latter is similar to the standard <code>UserDetailsService</code> but takes an <code>Authentication</code> object rather than just user name:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface AuthenticationUserDetailsService {
  UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException;
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This interface may have also other uses but with pre-authentication it allows access to the authorities which were packaged in the <code>Authentication</code> object, as we saw in the previous section. the <code>PreAuthenticatedGrantedAuthoritiesUserDetailsService</code> class does this. Alternatively, it may delegate to a standard <code>UserDetailsService</code> via the <code>UserDetailsByNameServiceWrapper</code> implementation.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="http403forbiddenentrypoint"><a class="anchor" href="#http403forbiddenentrypoint"></a>2.1.3. Http403ForbiddenEntryPoint</h4>
                        <div class="paragraph">
                            <p>The <code>AuthenticationEntryPoint</code> was discussed in the <a href="#tech-intro-auth-entry-point">technical overview</a> chapter. Normally it is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn`t apply. You would only configure the <code>ExceptionTranslationFilter</code> with an instance of this class if you aren`t using pre-authentication in combination with other authentication mechanisms. It will be called if the user is rejected by the <code>AbstractPreAuthenticatedProcessingFilter</code> resulting in a null authentication. It always returns a <code>403</code>-forbidden response code if called.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="concrete-implementations"><a class="anchor" href="#concrete-implementations"></a>2.2. Concrete Implementations</h3>
                    <div class="paragraph">
                        <p>X.509 authentication is covered in its <a href="#x509">own chapter</a>. Here we`ll look at some classes which provide support for other pre-authenticated scenarios.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="request-header-authentication-siteminder"><a class="anchor" href="#request-header-authentication-siteminder"></a>2.2.1. Request-Header Authentication (Siteminder)</h4>
                        <div class="paragraph">
                            <p>An external authentication system may supply information to the application by setting specific headers on the HTTP request. A well known example of this is Siteminder, which passes the username in a header called <code>SM_USER</code>. This mechanism is supported by the class <code>RequestHeaderAuthenticationFilter</code> which simply extracts the username from the header. It defaults to using the name <code>SM_USER</code> as the header name. See the Javadoc for more details.</p>
                        </div>
                        <div class="admonitionblock tip">
                            <table>
                                <tr>
                                    <td class="icon">
                                        <i class="icon-tip" title="Tip"></i>
                                    </td>
                                    <td class="content">
                                        <div class="paragraph">
                                            <p>Note that when using a system like this, the framework performs no authentication checks at all and it is <em>extremely</em> important that the external system is configured properly and protects all access to the application. If an attacker is able to forge the headers in their original request without this being detected then they could potentially choose any username they wished.</p>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="sect4">
                            <h5 id="siteminder-example-configuration"><a class="anchor" href="#siteminder-example-configuration"></a>Siteminder Example Configuration</h5>
                            <div class="paragraph">
                                <p>A typical configuration using this filter would look like this:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;security:http&gt;
  &lt;!-- Additional http configuration omitted --&gt;
  &lt;security:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" /&gt;
&lt;/security:http&gt;

&lt;bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter"&gt;
  &lt;property name="principalRequestHeader" value="SM_USER"/&gt;
  &lt;property name="authenticationManager" ref="authenticationManager" /&gt;
&lt;/bean&gt;

&lt;bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider"&gt;
  &lt;property name="preAuthenticatedUserDetailsService"&gt;
    &lt;bean id="userDetailsServiceWrapper"
          class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"&gt;
      &lt;property name="userDetailsService" ref="userDetailsService"/&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
&lt;/bean&gt;

&lt;security:authentication-manager alias="authenticationManager"&gt;
   &lt;security:authentication-provider ref="preauthAuthProvider" /&gt;
&lt;/security:authentication-manager&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>We`ve assumed here that the <a href="#ns-config">security namespace</a> is being used for configuration. It`s also assumed that you have added a <code>UserDetailsService</code> (called "userDetailsService") to your configuration to load the user`s roles.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="java-ee-container-authentication"><a class="anchor" href="#java-ee-container-authentication"></a>2.2.2. Java EE Container Authentication</h4>
                        <div class="paragraph">
                            <p>The class <code>J2eePreAuthenticatedProcessingFilter</code> will extract the username from the <code>userPrincipal</code> property of the <code>HttpServletRequest</code>. Use of this filter would usually be combined with the use of Java EE roles as described above in <a href="#j2ee-preauth-details">J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource</a>.</p>
                        </div>
                        <div class="paragraph">
                            <p>There is a sample application in the codebase which uses this approach, so get hold of the code from subversion and have a look at the application context file if you are interested. The code is in the <code>samples/preauth</code> directory.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="ldap"><a class="anchor" href="#ldap"></a>3. LDAP Authentication</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="ldap-overview"><a class="anchor" href="#ldap-overview"></a>3.1. Overview</h3>
                    <div class="paragraph">
                        <p>LDAP is often used by organizations as a central repository for user information and as an authentication service. It can also be used to store the role information for application users.</p>
                    </div>
                    <div class="paragraph">
                        <p>There are many different scenarios for how an LDAP server may be configured so Spring Security`s LDAP provider is fully configurable. It uses separate strategy interfaces for authentication and role retrieval and provides default implementations which can be configured to handle a wide range of situations.</p>
                    </div>
                    <div class="paragraph">
                        <p>You should be familiar with LDAP before trying to use it with Spring Security. The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server OpenLDAP: <a href="http://www.zytrax.com/books/ldap/">http://www.zytrax.com/books/ldap/</a>. Some familiarity with the JNDI APIs used to access LDAP from Java may also be useful. We don`t use any third-party LDAP libraries (Mozilla, JLDAP etc.) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations.</p>
                    </div>
                    <div class="paragraph">
                        <p>When using LDAP authentication, it is important to ensure that you configure LDAP connection pooling properly. If you are unfamiliar with how to do this, you can refer to the <a href="http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html">Java LDAP documentation</a>.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="using-ldap-with-spring-security"><a class="anchor" href="#using-ldap-with-spring-security"></a>3.2. Using LDAP with Spring Security</h3>
                    <div class="paragraph">
                        <p>LDAP authentication in Spring Security can be roughly divided into the following stages.</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>Obtaining the unique LDAP "Distinguished Name", or DN, from the login name. This will often mean performing a search in the directory, unless the exact mapping of usernames to DNs is known in advance. So a user might enter the name "joe" when logging in, but the actual name used to authenticate to LDAP will be the full DN, such as`uid=joe,ou=users,dc=springsource,dc=com`.</p>
                            </li>
                            <li>
                                <p>Authenticating the user, either by "binding" as that user or by performing a remote "compare" operation of the user`s password against the password attribute in the directory entry for the DN.</p>
                            </li>
                            <li>
                                <p>Loading the list of authorities for the user.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>The exception is when the LDAP directory is just being used to retrieve user information and authenticate against it locally. This may not be possible as directories are often set up with limited read access for attributes such as user passwords.</p>
                    </div>
                    <div class="paragraph">
                        <p>We will look at some configuration scenarios below. For full information on available configuration options, please consult the security namespace schema (information from which should be available in your XML editor).</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ldap-server"><a class="anchor" href="#ldap-server"></a>3.3. Configuring an LDAP Server</h3>
                    <div class="paragraph">
                        <p>The first thing you need to do is configure the server against which authentication should take place. This is done using the <code>&lt;ldap-server&gt;</code> element from the security namespace. This can be configured to point at an external LDAP server, using the <code>url</code> attribute:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;ldap-server url="ldap://springframework.org:389/dc=springframework,dc=org" /&gt;</code></pre>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="using-an-embedded-test-server"><a class="anchor" href="#using-an-embedded-test-server"></a>3.3.1. Using an Embedded Test Server</h4>
                        <div class="paragraph">
                            <p>The <code>&lt;ldap-server&gt;</code> element can also be used to create an embedded server, which can be very useful for testing and demonstrations. In this case you use it without the <code>url</code> attribute:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;ldap-server root="dc=springframework,dc=org"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Here we`ve specified that the root DIT of the directory should be "dc=springframework,dc=org", which is the default. Used this way, the namespace parser will create an embedded Apache Directory server and scan the classpath for any LDIF files, which it will attempt to load into the server. You can customize this behaviour using the <code>ldif</code> attribute, which defines an LDIF resource to be loaded:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;ldap-server ldif="classpath:users.ldif" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This makes it a lot easier to get up and running with LDAP, since it can be inconvenient to work all the time with an external server. It also insulates the user from the complex bean configuration needed to wire up an Apache Directory server. Using plain Spring Beans the configuration would be much more cluttered. You must have the necessary Apache Directory dependency jars available for your application to use. These can be obtained from the LDAP sample application.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="using-bind-authentication"><a class="anchor" href="#using-bind-authentication"></a>3.3.2. Using Bind Authentication</h4>
                        <div class="paragraph">
                            <p>This is the most common LDAP authentication scenario.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;ldap-authentication-provider user-dn-pattern="uid={0},ou=people"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. This is OK if all your users are stored under a single node in the directory. If instead you wished to configure an LDAP search filter to locate the user, you could use the following:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;ldap-authentication-provider user-search-filter="(uid={0})"
       user-search-base="ou=people"/&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>If used with the server definition above, this would perform a search under the DN <code>ou=people,dc=springframework,dc=org</code> using the value of the <code>user-search-filter</code> attribute as a filter. Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the <code>uid</code> attribute equal to the user name. If <code>user-search-base</code> isn`t supplied, the search will be performed from the root.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="loading-authorities"><a class="anchor" href="#loading-authorities"></a>3.3.3. Loading Authorities</h4>
                        <div class="paragraph">
                            <p>How authorities are loaded from groups in the LDAP directory is controlled by the following attributes.</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><code>group-search-base</code>. Defines the part of the directory tree under which group searches should be performed.</p>
                                </li>
                                <li>
                                    <p><code>group-role-attribute</code>. The attribute which contains the name of the authority defined by the group entry. Defaults to`cn`</p>
                                </li>
                                <li>
                                    <p><code>group-search-filter</code>. The filter which is used to search for group membership. The default is`uniqueMember={0}<code>, corresponding to the `groupOfUniqueNames</code> LDAP class <span class="footnote">[<a id="_footnoteref_21" class="footnote" href="#_footnote_21" title="View footnote.">21</a>]</span>. In this case, the substituted parameter is the full distinguished name of the user. The parameter <code>{1}</code> can be used if you want to filter on the login name.</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>So if we used the following configuration</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;ldap-authentication-provider user-dn-pattern="uid={0},ou=people"
        group-search-base="ou=groups" /&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>and authenticated successfully as user "ben", the subsequent loading of authorities would perform a search under the directory entry`ou=groups,dc=springframework,dc=org`, looking for entries which contain the attribute <code>uniqueMember</code> with value <code>uid=ben,ou=people,dc=springframework,dc=org</code>. By default the authority names will have the prefix <code>ROLE_</code> prepended. You can change this using the <code>role-prefix</code> attribute. If you don`t want any prefix, use <code>role-prefix="none"</code>. For more information on loading authorities, see the Javadoc for the <code>DefaultLdapAuthoritiesPopulator</code> class.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="implementation-classes"><a class="anchor" href="#implementation-classes"></a>3.4. Implementation Classes</h3>
                    <div class="paragraph">
                        <p>The namespace configuration options we`ve used above are simple to use and much more concise than using Spring beans explicitly. There are situations when you may need to know how to configure Spring Security LDAP directly in your application context. You may wish to customize the behaviour of some of the classes, for example. If you`re happy using namespace configuration then you can skip this section and the next one.</p>
                    </div>
                    <div class="paragraph">
                        <p>The main LDAP provider class, <code>LdapAuthenticationProvider</code>, doesn`t actually do much itself but delegates the work to two other beans, an <code>LdapAuthenticator</code> and an <code>LdapAuthoritiesPopulator</code> which are responsible for authenticating the user and retrieving the user`s set of <code>GrantedAuthority</code> s respectively.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-ldap-authenticators"><a class="anchor" href="#ldap-ldap-authenticators"></a>3.4.1. LdapAuthenticator Implementations</h4>
                        <div class="paragraph">
                            <p>The authenticator is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read them with the user`s own permissions.</p>
                        </div>
                        <div class="paragraph">
                            <p>There are currently two authentication strategies supplied with Spring Security:</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p>Authentication directly to the LDAP server ("bind" authentication).</p>
                                </li>
                                <li>
                                    <p>Password comparison, where the password supplied by the user is compared with the one stored in the repository. This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "compare" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved.</p>
                                </li>
                            </ul>
                        </div>
                        <div class="sect4">
                            <h5 id="ldap-ldap-authenticators-common"><a class="anchor" href="#ldap-ldap-authenticators-common"></a>Common Functionality</h5>
                            <div class="paragraph">
                                <p>Before it is possible to authenticate a user (by either strategy), the distinguished name (DN) has to be obtained from the login name supplied to the application. This can be done either by simple pattern-matching (by setting the <code>setUserDnPatterns</code> array property) or by setting the <code>userSearch</code> property. For the DN pattern-matching approach, a standard Java pattern format is used, and the login name will be substituted for the parameter <code>{0}</code>. The pattern should be relative to the DN that the configured <code>SpringSecurityContextSource</code> will bind to (see the section on <a href="#ldap-context-source">connecting to the LDAP server</a> for more information on this). For example, if you are using an LDAP server with the URL`ldap://monkeymachine.co.uk/dc=springframework,dc=org`, and have a pattern <code>uid={0},ou=greatapes</code>, then a login name of "gorilla" will map to a DN`uid=gorilla,ou=greatapes,dc=springframework,dc=org`. Each configured DN pattern will be tried in turn until a match is found. For information on using a search, see the section on <a href="#ldap-searchobjects">search objects</a> below. A combination of the two approaches can also be used - the patterns will be checked first and if no matching DN is found, the search will be used.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="ldap-ldap-authenticators-bind"><a class="anchor" href="#ldap-ldap-authenticators-bind"></a>BindAuthenticator</h5>
                            <div class="paragraph">
                                <p>The class <code>BindAuthenticator</code> in the package <code>org.springframework.security.ldap.authentication</code> implements the bind authentication strategy. It simply attempts to bind as the user.</p>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="ldap-ldap-authenticators-password"><a class="anchor" href="#ldap-ldap-authenticators-password"></a>PasswordComparisonAuthenticator</h5>
                            <div class="paragraph">
                                <p>The class <code>PasswordComparisonAuthenticator</code> implements the password comparison authentication strategy.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-context-source"><a class="anchor" href="#ldap-context-source"></a>3.4.2. Connecting to the LDAP Server</h4>
                        <div class="paragraph">
                            <p>The beans discussed above have to be able to connect to the server. They both have to be supplied with a <code>SpringSecurityContextSource</code> which is an extension of Spring LDAP`s <code>ContextSource</code>. Unless you have special requirements, you will usually configure a <code>DefaultSpringSecurityContextSource</code> bean, which can be configured with the URL of your LDAP server and optionally with the username and password of a "manager" user which will be used by default when binding to the server (instead of binding anonymously). For more information read the Javadoc for this class and for Spring LDAP`s <code>AbstractContextSource</code>.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-searchobjects"><a class="anchor" href="#ldap-searchobjects"></a>3.4.3. LDAP Search Objects</h4>
                        <div class="paragraph">
                            <p>Often a more complicated strategy than simple DN-matching is required to locate a user entry in the directory. This can be encapsulated in an <code>LdapUserSearch</code> instance which can be supplied to the authenticator implementations, for example, to allow them to locate a user. The supplied implementation is <code>FilterBasedLdapUserSearch</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="ldap-searchobjects-filter"><a class="anchor" href="#ldap-searchobjects-filter"></a>FilterBasedLdapUserSearch</h5>
                            <div class="paragraph">
                                <p>This bean uses an LDAP filter to match the user object in the directory. The process is explained in the Javadoc for the corresponding search method on the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/naming/directory/DirContext.html#search(javax.naming.Name,%20java.lang.String,%20java.lang.Object">http://java.sun.com/j2se/1.4.2/docs/api/javax/naming/directory/DirContext.html#search(javax.naming.Name,%20java.lang.String,%20java.lang.Object</a>,%20javax.naming.directory.SearchControls)[JDK DirContext class]. As explained there, the search filter can be supplied with parameters. For this class, the only valid parameter is <code>{0}</code> which will be replaced with the user`s login name.</p>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-authorities"><a class="anchor" href="#ldap-authorities"></a>3.4.4. LdapAuthoritiesPopulator</h4>
                        <div class="paragraph">
                            <p>After authenticating the user successfully, the <code>LdapAuthenticationProvider</code> will attempt to load a set of authorities for the user by calling the configured <code>LdapAuthoritiesPopulator</code> bean. The <code>DefaultLdapAuthoritiesPopulator</code> is an implementation which will load the authorities by searching the directory for groups of which the user is a member (typically these will be <code>groupOfNames</code> or <code>groupOfUniqueNames</code> entries in the directory). Consult the Javadoc for this class for more details on how it works.</p>
                        </div>
                        <div class="paragraph">
                            <p>If you want to use LDAP only for authentication, but load the authorities from a difference source (such as a database) then you can provide your own implementation of this interface and inject that instead.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-bean-config"><a class="anchor" href="#ldap-bean-config"></a>3.4.5. Spring Bean Configuration</h4>
                        <div class="paragraph">
                            <p>A typical configuration, using some of the beans we`ve discussed here, might look like this:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="contextSource"
        class="org.springframework.security.ldap.DefaultSpringSecurityContextSource"&gt;
  &lt;constructor-arg value="ldap://monkeymachine:389/dc=springframework,dc=org"/&gt;
  &lt;property name="userDn" value="cn=manager,dc=springframework,dc=org"/&gt;
  &lt;property name="password" value="password"/&gt;
&lt;/bean&gt;

&lt;bean id="ldapAuthProvider"
    class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider"&gt;
 &lt;constructor-arg&gt;
   &lt;bean class="org.springframework.security.ldap.authentication.BindAuthenticator"&gt;
     &lt;constructor-arg ref="contextSource"/&gt;
     &lt;property name="userDnPatterns"&gt;
       &lt;list&gt;&lt;value&gt;uid={0},ou=people&lt;/value&gt;&lt;/list&gt;
     &lt;/property&gt;
   &lt;/bean&gt;
 &lt;/constructor-arg&gt;
 &lt;constructor-arg&gt;
   &lt;bean
     class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator"&gt;
     &lt;constructor-arg ref="contextSource"/&gt;
     &lt;constructor-arg value="ou=groups"/&gt;
     &lt;property name="groupRoleAttribute" value="ou"/&gt;
   &lt;/bean&gt;
 &lt;/constructor-arg&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>This would set up the provider to access an LDAP server with URL <code>ldap://monkeymachine:389/dc=springframework,dc=org</code>. Authentication will be performed by attempting to bind with the DN`uid=&lt;user-login-name&gt;,ou=people,dc=springframework,dc=org`. After successful authentication, roles will be assigned to the user by searching under the DN <code>ou=groups,dc=springframework,dc=org</code> with the default filter <code>(member=&lt;user's-DN&gt;)</code>. The role name will be taken from the "ou" attribute of each match.</p>
                        </div>
                        <div class="paragraph">
                            <p>To configure a user search object, which uses the filter <code>(uid=&lt;user-login-name&gt;)</code> for use instead of the DN-pattern (or in addition to it), you would configure the following bean</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="userSearch"
    class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch"&gt;
  &lt;constructor-arg index="0" value=""/&gt;
  &lt;constructor-arg index="1" value="(uid={0})"/&gt;
  &lt;constructor-arg index="2" ref="contextSource" /&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>and use it by setting the <code>BindAuthenticator</code> bean`s <code>userSearch</code> property. The authenticator would then call the search object to obtain the correct user`s DN before attempting to bind as this user.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="ldap-custom-user-details"><a class="anchor" href="#ldap-custom-user-details"></a>3.4.6. LDAP Attributes and Customized UserDetails</h4>
                        <div class="paragraph">
                            <p>The net result of an authentication using <code>LdapAuthenticationProvider</code> is the same as a normal Spring Security authentication using the standard <code>UserDetailsService</code> interface. A <code>UserDetails</code> object is created and stored in the returned <code>Authentication</code> object. As with using a <code>UserDetailsService</code>, a common requirement is to be able to customize this implementation and add extra properties. When using LDAP, these will normally be attributes from the user entry. The creation of the <code>UserDetails</code> object is controlled by the provider`s <code>UserDetailsContextMapper</code> strategy, which is responsible for mapping user objects to and from LDAP context data:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>public interface UserDetailsContextMapper {

  UserDetails mapUserFromContext(DirContextOperations ctx, String username,
          Collection&lt;GrantedAuthority&gt; authorities);

  void mapUserToContext(UserDetails user, DirContextAdapter ctx);
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Only the first method is relevant for authentication. If you provide an implementation of this interface and inject it into the <code>LdapAuthenticationProvider</code>, you have control over exactly how the UserDetails object is created. The first parameter is an instance of Spring LDAP`s <code>DirContextOperations</code> which gives you access to the LDAP attributes which were loaded during authentication. the <code>username</code> parameter is the name used to authenticate and the final parameter is the collection of authorities loaded for the user by the configured`LdapAuthoritiesPopulator`.</p>
                        </div>
                        <div class="paragraph">
                            <p>The way the context data is loaded varies slightly depending on the type of authentication you are using. With the <code>BindAuthenticator</code>, the context returned from the bind operation will be used to read the attributes, otherwise the data will be read using the standard context obtained from the configured <code>ContextSource</code> (when a search is configured to locate the user, this will be the data returned by the search object).</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="ldap-active-directory"><a class="anchor" href="#ldap-active-directory"></a>3.5. Active Directory Authentication</h3>
                    <div class="paragraph">
                        <p>Active Directory supports its own non-standard authentication options, and the normal usage pattern doesn`t fit too cleanly with the standard <code>LdapAuthenticationProvider</code>. Typically authentication is performed using the domain username (in the form <code>user@domain</code>), rather than using an LDAP distinguished name. To make this easier, Spring Security 3.1 has an authentication provider which is customized for a typical Active Directory setup.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="activedirectoryldapauthenticationprovider"><a class="anchor" href="#activedirectoryldapauthenticationprovider"></a>3.5.1. ActiveDirectoryLdapAuthenticationProvider</h4>
                        <div class="paragraph">
                            <p>Configuring <code>ActiveDirectoryLdapAuthenticationProvider</code> is quite straightforward. You just need to supply the domain name and an LDAP URL supplying the address of the server <span class="footnote">[<a id="_footnoteref_22" class="footnote" href="#_footnote_22" title="View footnote.">22</a>]</span>. An example configuration would then look like this:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="adAuthenticationProvider"
  class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider"&gt;
    &lt;constructor-arg value="mydomain.com" /&gt;
    &lt;constructor-arg value="ldap://adserver.mydomain.com/" /&gt;
&lt;/bean&gt;
}</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Note that there is no need to specify a separate <code>ContextSource</code> in order to define the server location - the bean is completely self-contained. A user named "Sharon", for example, would then be able to authenticate by entering either the username <code>sharon</code> or the full Active Directory <code>userPrincipalName</code>, namely <code>sharon@mydomain.com</code>. The user`s directory entry will then be located, and the attributes returned for possible use in customizing the created <code>UserDetails</code> object (a <code>UserDetailsContextMapper</code> can be injected for this purpose, as described above). All interaction with the directory takes place with the identity of the user themselves. There is no concept of a "manager" user.</p>
                        </div>
                        <div class="paragraph">
                            <p>By default, the user authorities are obtained from the <code>memberOf</code> attribute values of the user entry. The authorities allocated to the user can again be customized using a <code>UserDetailsContextMapper</code>. You can also inject a <code>GrantedAuthoritiesMapper</code> into the provider instance to control the authorities which end up in the <code>Authentication</code> object.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="active-directory-error-codes"><a class="anchor" href="#active-directory-error-codes"></a>Active Directory Error Codes</h5>
                            <div class="paragraph">
                                <p>By default, a failed result will cause a standard Spring Security <code>BadCredentialsException</code>. If you set the property <code>convertSubErrorCodesToExceptions</code> to <code>true</code>, the exception messages will be parsed to attempt to extract the Active Directory-specific error code and raise a more specific exception. Check the class Javadoc for more information.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="taglibs"><a class="anchor" href="#taglibs"></a>4. JSP Tag Libraries</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs.</p>
                </div>
                <div class="sect2">
                    <h3 id="declaring-the-taglib"><a class="anchor" href="#declaring-the-taglib"></a>4.1. Declaring the Taglib</h3>
                    <div class="paragraph">
                        <p>To use any of the tags, you must have the security taglib declared in your JSP:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %&gt;</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="the-authorize-tag"><a class="anchor" href="#the-authorize-tag"></a>4.2. The authorize Tag</h3>
                    <div class="paragraph">
                        <p>This tag is used to determine whether its contents should be evaluated or not. In Spring Security 3.0, it can be used in two ways <span class="footnote">[<a id="_footnoteref_23" class="footnote" href="#_footnote_23" title="View footnote.">23</a>]</span>. The first approach uses a <a href="#el-access-web">web-security expression</a>, specified in the <code>access</code> attribute of the tag. The expression evaluation will be delegated to the <code>SecurityExpressionHandler&lt;FilterInvocation&gt;</code> defined in the application context (you should have web expressions enabled in your <code>&lt;http&gt;</code> namespace configuration to make sure this service is available). So, for example, you might have</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;sec:authorize access="hasRole('supervisor')"&gt;

  This content will only be visible to users who have the "supervisor" authority in their list of &lt;tt&gt;GrantedAuthority&lt;/tt&gt;s.

&lt;/sec:authorize&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>A common requirement is to only show a particular link, if the user is actually allowed to click it. How can we determine in advance whether something will be allowed? This tag can also operate in an alternative mode which allows you to define a particular URL as an attribute. If the user is allowed to invoke that URL, then the tag body will be evaluated, otherwise it will be skipped. So you might have something like</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;sec:authorize url="/admin"&gt;

  This content will only be visible to users who are authorized to send requests to the "/admin" URL.

&lt;/sec:authorize&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>To use this tag there must also be an instance of <code>WebInvocationPrivilegeEvaluator</code> in your application context. If you are using the namespace, one will automatically be registered. This is an instance of <code>DefaultWebInvocationPrivilegeEvaluator</code>, which creates a dummy web request for the supplied URL and invokes the security interceptor to see whether the request would succeed or fail. This allows you to delegate to the access-control setup you defined using <code>intercept-url</code> declarations within the <code>&lt;http&gt;</code> namespace configuration and saves having to duplicate the information (such as the required roles) within your JSPs. This approach can also be combined with a <code>method</code> attribute, supplying the HTTP method, for a more specific match.</p>
                    </div>
                    <div class="paragraph">
                        <p>The boolean result of evaluating the tag (whether it grants or denies access) can be stored in a page context scope variable by setting the <code>var</code> attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="disabling-tag-authorization-for-testing"><a class="anchor" href="#disabling-tag-authorization-for-testing"></a>4.2.1. Disabling Tag Authorization for Testing</h4>
                        <div class="paragraph">
                            <p>Hiding a link in a page for unauthorized users doesn`t prevent them from accessing the URL. They could just type it into their browser directly, for example. As part of your testing process, you may want to reveal the hidden areas in order to check that links really are secured at the back end. If you set the system property <code>spring.security.disableUISecurity</code> to <code>true</code>, the <code>authorize</code> tag will still run but will not hide its contents. By default it will also surround the content with <code>&lt;span class="securityHiddenUI"&gt;...&lt;/span&gt;</code> tags. This allows you to display "hidden" content with a particular CSS style such as a different background colour. Try running the "tutorial" sample application with this property enabled, for example.</p>
                        </div>
                        <div class="paragraph">
                            <p>You can also set the properties <code>spring.security.securedUIPrefix</code> and <code>spring.security.securedUISuffix</code> if you want to change surrounding text from the default <code>span</code> tags (or use empty strings to remove it completely).</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="the-authentication-tag"><a class="anchor" href="#the-authentication-tag"></a>4.3. The authentication Tag</h3>
                    <div class="paragraph">
                        <p>This tag allows access to the current <code>Authentication</code> object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the <code>principal</code> property of the <code>Authentication</code> is an instance of Spring Security`s <code>UserDetails</code> object, then using <code>&lt;sec:authentication property="principal.username" /&gt;</code> will render the name of the current user.</p>
                    </div>
                    <div class="paragraph">
                        <p>Of course, it isn`t necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. You can access the <code>Authentication</code> object in your MVC controller (by calling <code>SecurityContextHolder.getContext().getAuthentication()</code>) and add the data directly to your model for rendering by the view.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="the-accesscontrollist-tag"><a class="anchor" href="#the-accesscontrollist-tag"></a>4.4. The accesscontrollist Tag</h3>
                    <div class="paragraph">
                        <p>This tag is only valid when used with Spring Security`s ACL module. It checks a comma-separated list of required permissions for a specified domain object. If the current user has any of those permissions, then the tag body will be evaluated. If they don`t, it will be skipped. An example might be</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}"&gt;

  This will be shown if the user has either of the permissions represented by the values "1" or "2" on the given object.

&lt;/sec:accesscontrollist&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The permissions are passed to the <code>PermissionFactory</code> defined in the application context, converting them to ACL <code>Permission</code> instances, so they may be any format which is supported by the factory - they don`t have to be integers, they could be strings like <code>READ</code> or <code>WRITE</code>. If no <code>PermissionFactory</code> is found, an instance of <code>DefaultPermissionFactory</code> will be used. The <code>AclService</code> from the application context will be used to load the <code>Acl</code> instance for the supplied object. The <code>Acl</code> will be invoked with the required permissions to check if any of them are granted.</p>
                    </div>
                    <div class="paragraph">
                        <p>This tag also supports the <code>var</code> attribute, in the same way as the <code>authorize</code> tag.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="the-csrfinput-tag"><a class="anchor" href="#the-csrfinput-tag"></a>4.5. The csrfInput Tag</h3>
                    <div class="paragraph">
                        <p>If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for the CSRF protection token. If CSRF protection is not enabled, this tag outputs nothing.</p>
                    </div>
                    <div class="paragraph">
                        <p>Normally Spring Security automatically inserts a CSRF form field for any <code>&lt;form:form&gt;</code> tags you use, but if for some reason you cannot use <code>&lt;form:form&gt;</code>, <code>csrfInput</code> is a handy replacement.</p>
                    </div>
                    <div class="paragraph">
                        <p>You should place this tag within an HTML <code>&lt;form&gt;&lt;/form&gt;</code> block, where you would normally place other input fields. Do NOT place this tag within a Spring <code>&lt;form:form&gt;&lt;/form:form&gt;</code> block—Spring Security handles Spring forms automatically.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>    &lt;form method="post" action="/do/something"&gt;
        &lt;sec:csrfInput /&gt;
        Name:&lt;br /&gt;
        &lt;input type="text" name="name" /&gt;
        ...
    &lt;/form&gt;</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="the-csrfmetatags-tag"><a class="anchor" href="#the-csrfmetatags-tag"></a>4.6. The csrfMetaTags Tag</h3>
                    <div class="paragraph">
                        <p>If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form field and header names and CSRF protection token value. These meta tags are useful for employing CSRF protection within JavaScript in your applications.</p>
                    </div>
                    <div class="paragraph">
                        <p>You should place <code>csrfMetaTags</code> within an HTML <code>&lt;head&gt;&lt;/head&gt;</code> block, where you would normally place other meta tags. Once you use this tag, you can access the form field name, header name, and token value easily using JavaScript. JQuery is used in this example to make the task easier.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;CSRF Protected JavaScript Page&lt;/title&gt;
        &lt;meta name="description" content="This is the description for this page" /&gt;
        &lt;sec:csrfMetaTags /&gt;
        &lt;script type="text/javascript" language="javascript"&gt;

            var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
            var csrfHeader = $("meta[name='_csrf_header']").attr("content");
            var csrfToken = $("meta[name='_csrf']").attr("content");

            // using XMLHttpRequest directly to send an x-www-form-urlencoded request
            var ajax = new XMLHttpRequest();
            ajax.open("POST", "http://www.example.org/do/something", true);
            ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded data");
            ajax.send(csrfParameter + "=" + csrfToken + "&amp;name=John&amp;...");

            // using XMLHttpRequest directly to send a non-x-www-form-urlencoded request
            var ajax = new XMLHttpRequest();
            ajax.open("POST", "http://www.example.org/do/something", true);
            ajax.setRequestHeader(csrfHeader, csrfToken);
            ajax.send("...");

            // using JQuery to send an x-www-form-urlencoded request
            var data = {};
            data[csrfParameter] = csrfToken;
            data["name"] = "John";
            ...
            $.ajax({
                url: "http://www.example.org/do/something",
                type: "POST",
                data: data,
                ...
            });

            // using JQuery to send a non-x-www-form-urlencoded request
            var headers = {};
            headers[csrfHeader] = csrfToken;
            $.ajax({
                url: "http://www.example.org/do/something",
                type: "POST",
                headers: headers,
                ...
            });

        &lt;script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        ...
    &lt;/body&gt;
&lt;/html&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>If CSRF protection is not enabled, <code>csrfMetaTags</code> outputs nothing.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="jaas"><a class="anchor" href="#jaas"></a>5. Java Authentication and Authorization Service (JAAS) Provider</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="overview-2"><a class="anchor" href="#overview-2"></a>5.1. Overview</h3>
                    <div class="paragraph">
                        <p>Spring Security provides a package able to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). This package is discussed in detail below.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jaas-abstractjaasauthenticationprovider"><a class="anchor" href="#jaas-abstractjaasauthenticationprovider"></a>5.2. AbstractJaasAuthenticationProvider</h3>
                    <div class="paragraph">
                        <p>The <code>AbstractJaasAuthenticationProvider</code> is the basis for the provided JAAS <code>AuthenticationProvider</code> implementations. Subclasses must implement a method that creates the <code>LoginContext</code>. The <code>AbstractJaasAuthenticationProvider</code> has a number of dependencies that can be injected into it that are discussed below.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="jaas-callbackhandler"><a class="anchor" href="#jaas-callbackhandler"></a>5.2.1. JAAS CallbackHandler</h4>
                        <div class="paragraph">
                            <p>Most JAAS <code>LoginModule</code> s require a callback of some sort. These callbacks are usually used to obtain the username and password from the user.</p>
                        </div>
                        <div class="paragraph">
                            <p>In a Spring Security deployment, Spring Security is responsible for this user interaction (via the authentication mechanism). Thus, by the time the authentication request is delegated through to JAAS, Spring Security`s authentication mechanism will already have fully-populated an <code>Authentication</code> object containing all the information required by the JAAS <code>LoginModule</code>.</p>
                        </div>
                        <div class="paragraph">
                            <p>Therefore, the JAAS package for Spring Security provides two default callback handlers, <code>JaasNameCallbackHandler</code> and <code>JaasPasswordCallbackHandler</code>. Each of these callback handlers implement <code>JaasAuthenticationCallbackHandler</code>. In most cases these callback handlers can simply be used without understanding the internal mechanics.</p>
                        </div>
                        <div class="paragraph">
                            <p>For those needing full control over the callback behavior, internally <code>AbstractJaasAuthenticationProvider</code> wraps these <code>JaasAuthenticationCallbackHandler</code> s with an <code>InternalCallbackHandler</code>. The <code>InternalCallbackHandler</code> is the class that actually implements JAAS normal <code>CallbackHandler</code> interface. Any time that the JAAS <code>LoginModule</code> is used, it is passed a list of application context configured <code>InternalCallbackHandler</code> s. If the <code>LoginModule</code> requests a callback against the <code>InternalCallbackHandler</code> s, the callback is in-turn passed to the <code>JaasAuthenticationCallbackHandler</code> s being wrapped.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="jaas-authoritygranter"><a class="anchor" href="#jaas-authoritygranter"></a>5.2.2. JAAS AuthorityGranter</h4>
                        <div class="paragraph">
                            <p>JAAS works with principals. Even "roles" are represented as principals in JAAS. Spring Security, on the other hand, works with <code>Authentication</code> objects. Each <code>Authentication</code> object contains a single principal, and multiple <code>GrantedAuthority</code> s. To facilitate mapping between these different concepts, Spring Security`s JAAS package includes an <code>AuthorityGranter</code> interface.</p>
                        </div>
                        <div class="paragraph">
                            <p>An <code>AuthorityGranter</code> is responsible for inspecting a JAAS principal and returning a set of <code>String</code> s, representing the authorities assigned to the principal. For each returned authority string, the <code>AbstractJaasAuthenticationProvider</code> creates a <code>JaasGrantedAuthority</code> (which implements Spring Security`s <code>GrantedAuthority</code> interface) containing the authority string and the JAAS principal that the <code>AuthorityGranter</code> was passed. The <code>AbstractJaasAuthenticationProvider</code> obtains the JAAS principals by firstly successfully authenticating the user`s credentials using the JAAS <code>LoginModule</code>, and then accessing the <code>LoginContext</code> it returns. A call to <code>LoginContext.getSubject().getPrincipals()</code> is made, with each resulting principal passed to each <code>AuthorityGranter</code> defined against the <code>AbstractJaasAuthenticationProvider.setAuthorityGranters(List)</code> property.</p>
                        </div>
                        <div class="paragraph">
                            <p>Spring Security does not include any production <code>AuthorityGranter</code> s given that every JAAS principal has an implementation-specific meaning. However, there is a <code>TestAuthorityGranter</code> in the unit tests that demonstrates a simple <code>AuthorityGranter</code> implementation.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jaas-defaultjaasauthenticationprovider"><a class="anchor" href="#jaas-defaultjaasauthenticationprovider"></a>5.3. DefaultJaasAuthenticationProvider</h3>
                    <div class="paragraph">
                        <p>The <code>DefaultJaasAuthenticationProvider</code> allows a JAAS <code>Configuration</code> object to be injected into it as a dependency. It then creates a <code>LoginContext</code> using the injected JAAS <code>Configuration</code>. This means that <code>DefaultJaasAuthenticationProvider</code> is not bound any particular implementation of <code>Configuration</code> as <code>JaasAuthenticationProvider</code> is.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="jaas-inmemoryconfiguration"><a class="anchor" href="#jaas-inmemoryconfiguration"></a>5.3.1. InMemoryConfiguration</h4>
                        <div class="paragraph">
                            <p>In order to make it easy to inject a <code>Configuration</code> into <code>DefaultJaasAuthenticationProvider</code>, a default in memory implementation named <code>InMemoryConfiguration</code> is provided. The implementation constructor accepts a <code>Map</code> where each key represents a login configuration name and the value represents an <code>Array</code> of <code>AppConfigurationEntry</code> s. <code>InMemoryConfiguration</code> also supports a default <code>Array</code> of <code>AppConfigurationEntry</code> objects that will be used if no mapping is found within the provided <code>Map</code>. For details, refer to the class level javadoc of <code>InMemoryConfiguration</code>.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="jaas-djap-config"><a class="anchor" href="#jaas-djap-config"></a>5.3.2. DefaultJaasAuthenticationProvider Example Configuration</h4>
                        <div class="paragraph">
                            <p>While the Spring configuration for <code>InMemoryConfiguration</code> can be more verbose than the standarad JAAS configuration files, using it in conjuction with <code>DefaultJaasAuthenticationProvider</code> is more flexible than <code>JaasAuthenticationProvider</code> since it not dependant on the default <code>Configuration</code> implementation.</p>
                        </div>
                        <div class="paragraph">
                            <p>An example configuration of <code>DefaultJaasAuthenticationProvider</code> using <code>InMemoryConfiguration</code> is provided below. Note that custom implementations of <code>Configuration</code> can easily be injected into <code>DefaultJaasAuthenticationProvider</code> as well.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="jaasAuthProvider"
   class="org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProvider"&gt;
 &lt;property name="configuration"&gt;
  &lt;bean class="org.springframework.security.authentication.jaas.memory.InMemoryConfiguration"&gt;
   &lt;constructor-arg&gt;
    &lt;map&gt;
     &lt;!--
       SPRINGSECURITY is the default loginContextName
       for AbstractJaasAuthenticationProvider
     --&gt;
     &lt;entry key="SPRINGSECURITY"&gt;
      &lt;array&gt;
       &lt;bean class="javax.security.auth.login.AppConfigurationEntry"&gt;
        &lt;constructor-arg value="sample.SampleLoginModule" /&gt;
         &lt;constructor-arg&gt;
          &lt;util:constant static-field=
            "javax.security.auth.login.AppConfigurationEntry$LoginModuleControlFlag.REQUIRED"/&gt;
         &lt;/constructor-arg&gt;
         &lt;constructor-arg&gt;
          &lt;map&gt;&lt;/map&gt;
         &lt;/constructor-arg&gt;
        &lt;/bean&gt;
       &lt;/array&gt;
      &lt;/entry&gt;
     &lt;/map&gt;
    &lt;/constructor-arg&gt;
   &lt;/bean&gt;
  &lt;/property&gt;
  &lt;property name="authorityGranters"&gt;
   &lt;list&gt;
    &lt;!-- You will need to write your own implementation of AuthorityGranter --&gt;
    &lt;bean class="org.springframework.security.authentication.jaas.TestAuthorityGranter"/&gt;
   &lt;/list&gt;
  &lt;/property&gt;
&lt;/bean&gt;
</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jaas-jaasauthenticationprovider"><a class="anchor" href="#jaas-jaasauthenticationprovider"></a>5.4. JaasAuthenticationProvider</h3>
                    <div class="paragraph">
                        <p>The <code>JaasAuthenticationProvider</code> assumes the default <code>Configuration</code> is an instance of <a href="http://download.oracle.com/javase/1.4.2/docs/guide/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html"> ConfigFile</a>. This assumption is made in order to attempt to update the <code>Configuration</code>. The <code>JaasAuthenticationProvider</code> then uses the default <code>Configuration</code> to create the <code>LoginContext</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>Let`s assume we have a JAAS login configuration file, <code>/WEB-INF/login.conf</code>, with the following contents:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint txt language-txt"><code>JAASTest {
    sample.SampleLoginModule required;
};</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Like all Spring Security beans, the <code>JaasAuthenticationProvider</code> is configured via the application context. The following definitions would correspond to the above JAAS login configuration file:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="jaasAuthenticationProvider"
   class="org.springframework.security.authentication.jaas.JaasAuthenticationProvider"&gt;
 &lt;property name="loginConfig" value="/WEB-INF/login.conf"/&gt;
 &lt;property name="loginContextName" value="JAASTest"/&gt;
 &lt;property name="callbackHandlers"&gt;
  &lt;list&gt;
   &lt;bean
     class="org.springframework.security.authentication.jaas.JaasNameCallbackHandler"/&gt;
   &lt;bean
     class="org.springframework.security.authentication.jaas.JaasPasswordCallbackHandler"/&gt;
  &lt;/list&gt;
  &lt;/property&gt;
  &lt;property name="authorityGranters"&gt;
    &lt;list&gt;
      &lt;bean class="org.springframework.security.authentication.jaas.TestAuthorityGranter"/&gt;
    &lt;/list&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="jaas-apiprovision"><a class="anchor" href="#jaas-apiprovision"></a>5.5. Running as a Subject</h3>
                    <div class="paragraph">
                        <p>If configured, the <code>JaasApiIntegrationFilter</code> will attempt to run as the <code>Subject</code> on the <code>JaasAuthenticationToken</code>. This means that the <code>Subject</code> can be accessed using:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>Subject subject = Subject.getSubject(AccessController.getContext());</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>This integration can easily be configured using the <a href="#nsa-http-jaas-api-provision">jaas-api-provision</a> attribute. This feature is useful when integrating with legacy or external API`s that rely on the JAAS Subject being populated.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="cas"><a class="anchor" href="#cas"></a>6. CAS Authentication</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="cas-overview"><a class="anchor" href="#cas-overview"></a>6.1. Overview</h3>
                    <div class="paragraph">
                        <p>JA-SIG produces an enterprise-wide single sign on system known as CAS. Unlike other initiatives, JA-SIG`s Central Authentication Service is open source, widely used, simple to understand, platform independent, and supports proxy capabilities. Spring Security fully supports CAS, and provides an easy migration path from single-application deployments of Spring Security through to multiple-application deployments secured by an enterprise-wide CAS server.</p>
                    </div>
                    <div class="paragraph">
                        <p>You can learn more about CAS at <a href="http://www.ja-sig.org/cas">http://www.ja-sig.org/cas</a>. You will also need to visit this site to download the CAS Server files.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="cas-how-it-works"><a class="anchor" href="#cas-how-it-works"></a>6.2. How CAS Works</h3>
                    <div class="paragraph">
                        <p>Whilst the CAS web site contains documents that detail the architecture of CAS, we present the general overview again here within the context of Spring Security. Spring Security 3.x supports CAS 3. At the time of writing, the CAS server was at version 3.4.</p>
                    </div>
                    <div class="paragraph">
                        <p>Somewhere in your enterprise you will need to setup a CAS server. The CAS server is simply a standard WAR file, so there isn`t anything difficult about setting up your server. Inside the WAR file you will customise the login and other single sign on pages displayed to users.</p>
                    </div>
                    <div class="paragraph">
                        <p>When deploying a CAS 3.4 server, you will also need to specify an <code>AuthenticationHandler</code> in the <code>deployerConfigContext.xml</code> included with CAS. The <code>AuthenticationHandler</code> has a simple method that returns a boolean as to whether a given set of Credentials is valid. Your <code>AuthenticationHandler</code> implementation will need to link into some type of backend authentication repository, such as an LDAP server or database. CAS itself includes numerous <code>AuthenticationHandler</code> s out of the box to assist with this. When you download and deploy the server war file, it is set up to successfully authenticate users who enter a password matching their username, which is useful for testing.</p>
                    </div>
                    <div class="paragraph">
                        <p>Apart from the CAS server itself, the other key players are of course the secure web applications deployed throughout your enterprise. These web applications are known as "services". There are three types of services. Those that authenticate service tickets, those that can obtain proxy tickets, and those that authenticate proxy tickets. Authenticating a proxy ticket differs because the list of proxies must be validated and often times a proxy ticket can be reused.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="cas-sequence"><a class="anchor" href="#cas-sequence"></a>6.2.1. Spring Security and CAS Interaction Sequence</h4>
                        <div class="paragraph">
                            <p>The basic interaction between a web browser, CAS server and a Spring Security-secured service is as follows:</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p>The web user is browsing the service`s public pages. CAS or Spring Security is not involved.</p>
                                </li>
                                <li>
                                    <p>The user eventually requests a page that is either secure or one of the beans it uses is secure. Spring Security`s <code>ExceptionTranslationFilter</code> will detect the <code>AccessDeniedException</code> or <code>AuthenticationException</code>.</p>
                                </li>
                                <li>
                                    <p>Because the user`s <code>Authentication</code> object (or lack thereof) caused an <code>AuthenticationException</code>, the <code>ExceptionTranslationFilter</code> will call the configured <code>AuthenticationEntryPoint</code>. If using CAS, this will be the <code>CasAuthenticationEntryPoint</code> class.</p>
                                </li>
                                <li>
                                    <p>The <code>CasAuthenticationEntryPoint</code> will redirect the user`s browser to the CAS server. It will also indicate a <code>service</code> parameter, which is the callback URL for the Spring Security service (your application). For example, the URL to which the browser is redirected might be <a href="https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check">https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check</a>.</p>
                                </li>
                                <li>
                                    <p>After the user`s browser redirects to CAS, they will be prompted for their username and password. If the user presents a session cookie which indicates they`ve previously logged on, they will not be prompted to login again (there is an exception to this procedure, which we`ll cover later). CAS will use the <code>PasswordHandler</code> (or <code>AuthenticationHandler</code> if using CAS 3.0) discussed above to decide whether the username and password is valid.</p>
                                </li>
                                <li>
                                    <p>Upon successful login, CAS will redirect the user`s browser back to the original service. It will also include a <code>ticket</code> parameter, which is an opaque string representing the "service ticket". Continuing our earlier example, the URL the browser is redirected to might be <a href="https://server3.company.com/webapp/j_spring_cas_security_check?ticket=ST-0-ER94xMJmn6pha35CQRoZ">https://server3.company.com/webapp/j_spring_cas_security_check?ticket=ST-0-ER94xMJmn6pha35CQRoZ</a>.</p>
                                </li>
                                <li>
                                    <p>Back in the service web application, the <code>CasAuthenticationFilter</code> is always listening for requests to <code>/j_spring_cas_security_check</code> (this is configurable, but we`ll use the defaults in this introduction). The processing filter will construct a <code>UsernamePasswordAuthenticationToken</code> representing the service ticket. The principal will be equal to <code>CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER</code>, whilst the credentials will be the service ticket opaque value. This authentication request will then be handed to the configured <code>AuthenticationManager</code>.</p>
                                </li>
                                <li>
                                    <p>The <code>AuthenticationManager</code> implementation will be the <code>ProviderManager</code>, which is in turn configured with the <code>CasAuthenticationProvider</code>. The <code>CasAuthenticationProvider</code> only responds to <code>UsernamePasswordAuthenticationToken</code> s containing the CAS-specific principal (such as <code>CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER</code>) and <code>CasAuthenticationToken</code> s (discussed later).</p>
                                </li>
                                <li>
                                    <p><code>CasAuthenticationProvider</code> will validate the service ticket using a <code>TicketValidator</code> implementation. This will typically be a <code>Cas20ServiceTicketValidator</code> which is one of the classes included in the CAS client library. In the event the application needs to validate proxy tickets, the <code>Cas20ProxyTicketValidator</code> is used. The <code>TicketValidator</code> makes an HTTPS request to the CAS server in order to validate the service ticket. It may also include a proxy callback URL, which is included in this example: <a href="https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check&amp;ticket=ST-0-ER94xMJmn6pha35CQRoZ&amp;pgtUrl=https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor">https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check&amp;ticket=ST-0-ER94xMJmn6pha35CQRoZ&amp;pgtUrl=https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor</a>.</p>
                                </li>
                                <li>
                                    <p>Back on the CAS server, the validation request will be received. If the presented service ticket matches the service URL the ticket was issued to, CAS will provide an affirmative response in XML indicating the username. If any proxy was involved in the authentication (discussed below), the list of proxies is also included in the XML response.</p>
                                </li>
                                <li>
                                    <p>[OPTIONAL] If the request to the CAS validation service included the proxy callback URL (in the <code>pgtUrl</code> parameter), CAS will include a <code>pgtIou</code> string in the XML response. This <code>pgtIou</code> represents a proxy-granting ticket IOU. The CAS server will then create its own HTTPS connection back to the <code>pgtUrl</code>. This is to mutually authenticate the CAS server and the claimed service URL. The HTTPS connection will be used to send a proxy granting ticket to the original web application. For example, <a href="https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&amp;pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH">https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&amp;pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH</a>.</p>
                                </li>
                                <li>
                                    <p>The <code>Cas20TicketValidator</code> will parse the XML received from the CAS server. It will return to the <code>CasAuthenticationProvider</code> a <code>TicketResponse</code>, which includes the username (mandatory), proxy list (if any were involved), and proxy-granting ticket IOU (if the proxy callback was requested).</p>
                                </li>
                                <li>
                                    <p>Next <code>CasAuthenticationProvider</code> will call a configured <code>CasProxyDecider</code>. The <code>CasProxyDecider</code> indicates whether the proxy list in the <code>TicketResponse</code> is acceptable to the service. Several implementations are provided with Spring Security: <code>RejectProxyTickets</code>, <code>AcceptAnyCasProxy</code> and <code>NamedCasProxyDecider</code>. These names are largely self-explanatory, except <code>NamedCasProxyDecider</code> which allows a <code>List</code> of trusted proxies to be provided.</p>
                                </li>
                                <li>
                                    <p><code>CasAuthenticationProvider</code> will next request a <code>AuthenticationUserDetailsService</code> to load the <code>GrantedAuthority</code> objects that apply to the user contained in the <code>Assertion</code>.</p>
                                </li>
                                <li>
                                    <p>If there were no problems, <code>CasAuthenticationProvider</code> constructs a <code>CasAuthenticationToken</code> including the details contained in the <code>TicketResponse</code> and the `GrantedAuthority`s.</p>
                                </li>
                                <li>
                                    <p>Control then returns to <code>CasAuthenticationFilter</code>, which places the created <code>CasAuthenticationToken</code> in the security context.</p>
                                </li>
                                <li>
                                    <p>The user`s browser is redirected to the original page that caused the <code>AuthenticationException</code> (or a <a href="#form-login-flow-handling">custom destination</a> depending on the configuration).</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>It`s good that you`re still here! Let`s now look at how this is configured</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="cas-client"><a class="anchor" href="#cas-client"></a>6.3. Configuration of CAS Client</h3>
                    <div class="paragraph">
                        <p>The web application side of CAS is made easy due to Spring Security. It is assumed you already know the basics of using Spring Security, so these are not covered again below. We`ll assume a namespace based configuration is being used and add in the CAS beans as required. Each section builds upon the previous section. A full<a href="#cas-sample">CAS sample application</a> can be found in the Spring Security Samples.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="cas-st"><a class="anchor" href="#cas-st"></a>6.3.1. Service Ticket Authentication</h4>
                        <div class="paragraph">
                            <p>This section describes how to setup Spring Security to authenticate Service Tickets. Often times this is all a web application requires. You will need to add a <code>ServiceProperties</code> bean to your application context. This represents your CAS service:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="serviceProperties"
      class="org.springframework.security.cas.ServiceProperties"&gt;
  &lt;property name="service"
      value="https://localhost:8443/cas-sample/j_spring_cas_security_check"/&gt;
  &lt;property name="sendRenew" value="false"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>service</code> must equal a URL that will be monitored by the <code>CasAuthenticationFilter</code>. The <code>sendRenew</code> defaults to false, but should be set to true if your application is particularly sensitive. What this parameter does is tell the CAS login service that a single sign on login is unacceptable. Instead, the user will need to re-enter their username and password in order to gain access to the service.</p>
                        </div>
                        <div class="paragraph">
                            <p>The following beans should be configured to commence the CAS authentication process (assuming you`re using a namespace configuration):</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;security:http entry-point-ref="casEntryPoint"&gt;
 ...
   &lt;security:custom-filter position="CAS_FILTER" ref="casFilter" /&gt;
&lt;/security:http&gt;

&lt;bean id="casFilter"
      class="org.springframework.security.cas.web.CasAuthenticationFilter"&gt;
  &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
&lt;/bean&gt;

&lt;bean id="casEntryPoint"
      class="org.springframework.security.cas.web.CasAuthenticationEntryPoint"&gt;
  &lt;property name="loginUrl" value="https://localhost:9443/cas/login"/&gt;
  &lt;property name="serviceProperties" ref="serviceProperties"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>For CAS to operate, the <code>ExceptionTranslationFilter</code> must have its <code>authenticationEntryPoint</code> property set to the <code>CasAuthenticationEntryPoint</code> bean. This can easily be done using <a href="#ns-entry-point-ref">entry-point-ref</a> as is done in the example above. The <code>CasAuthenticationEntryPoint</code> must refer to the <code>ServiceProperties</code> bean (discussed above), which provides the URL to the enterprise`s CAS login server. This is where the user`s browser will be redirected.</p>
                        </div>
                        <div class="paragraph">
                            <p>The <code>CasAuthenticationFilter</code> has very similar properties to the <code>UsernamePasswordAuthenticationFilter</code> (used for form-based logins). You can use these properties to customize things like behavior for authentication success and failure.</p>
                        </div>
                        <div class="paragraph">
                            <p>Next you need to add a <code>CasAuthenticationProvider</code> and its collaborators:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;security:authentication-manager alias="authenticationManager"&gt;
  &lt;security:authentication-provider ref="casAuthenticationProvider" /&gt;
&lt;/security:authentication-manager&gt;

&lt;bean id="casAuthenticationProvider"
      class="org.springframework.security.cas.authentication.CasAuthenticationProvider"&gt;
  &lt;property name="authenticationUserDetailsService"&gt;
    &lt;bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"&gt;
      &lt;constructor-arg ref="userService" /&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
  &lt;property name="serviceProperties" ref="serviceProperties" /&gt;
  &lt;property name="ticketValidator"&gt;
    &lt;bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator"&gt;
      &lt;constructor-arg index="0" value="https://localhost:9443/cas" /&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
  &lt;property name="key" value="an_id_for_this_auth_provider_only"/&gt;
&lt;/bean&gt;

&lt;security:user-service id="userService"&gt;
  &lt;security:user name="joe" password="joe" authorities="ROLE_USER" /&gt;
  ...
&lt;/security:user-service&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>CasAuthenticationProvider</code> uses a <code>UserDetailsService</code> instance to load the authorities for a user, once they have been authenticated by CAS. We`ve shown a simple in-memory setup here. Note that the <code>CasAuthenticationProvider</code> does not actually use the password for authentication, but it does use the authorities.</p>
                        </div>
                        <div class="paragraph">
                            <p>The beans are all reasonably self-explanatory if you refer back to the <a href="#cas-how-it-works">How CAS Works</a> section.</p>
                        </div>
                        <div class="paragraph">
                            <p>This completes the most basic configuration for CAS. If you haven`t made any mistakes, your web application should happily work within the framework of CAS single sign on. No other parts of Spring Security need to be concerned about the fact CAS handled authentication. In the following sections we will discuss some (optional) more advanced configurations.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="cas-singlelogout"><a class="anchor" href="#cas-singlelogout"></a>6.3.2. Single Logout</h4>
                        <div class="paragraph">
                            <p>The CAS protocol supports Single Logout and can be easily added to your Spring Security configuration. Below are updates to the Spring Security configuration that handle Single Logout</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;security:http entry-point-ref="casEntryPoint"&gt;
  ...
  &lt;security:logout logout-success-url="/cas-logout.jsp"/&gt;
  &lt;security:custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/&gt;
  &lt;security:custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/&gt;
&lt;/security:http&gt;

&lt;!-- This filter handles a Single Logout Request from the CAS Server --&gt;
&lt;bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/&gt;

&lt;!-- This filter redirects to the CAS Server to signal Single Logout should be performed --&gt;
&lt;bean id="requestSingleLogoutFilter"
      class="org.springframework.security.web.authentication.logout.LogoutFilter"&gt;
  &lt;constructor-arg value="https://localhost:9443/cas/logout"/&gt;
  &lt;constructor-arg&gt;
    &lt;bean class=
          "org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/&gt;
  &lt;/constructor-arg&gt;
  &lt;property name="filterProcessesUrl" value="/j_spring_cas_security_logout"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The <code>logout</code> element logs the user out of the local application, but does not terminate the session with the CAS server or any other applications that have been logged into. The <code>requestSingleLogoutFilter</code> filter will allow the url of <code>/spring_security_cas_logout</code> to be requested to redirect the application to the configured CAS Server logout url. Then the CAS Server will send a Single Logout request to all the services that were signed into. The <code>singleLogoutFilter</code> handles the Single Logout request by looking up the <code>HttpSession</code> in a static <code>Map</code> and then invalidating it.</p>
                        </div>
                        <div class="paragraph">
                            <p>It might be confusing why both the <code>logout</code> element and the <code>singleLogoutFilter</code> are needed. It is considered best practice to logout locally first since the <code>SingleSignOutFilter</code> just stores the <code>HttpSession</code> in a static <code>Map</code> in order to call invalidate on it. With the configuration above, the flow of logout would be:</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p>The user requests <code>/j_spring_security_logout</code> which would log the user out of the local application and send the user to the logout success page.</p>
                                </li>
                                <li>
                                    <p>The logout success page, <code>/cas-logout.jsp</code>, should instruct the user to click a link pointing to <code>/j_spring_cas_security_logout</code> in order to logout out of all applications.</p>
                                </li>
                                <li>
                                    <p>When the user clicks the link, the user is redirected to the CAS single logout URL (<a href="https://localhost:9443/cas/logout">https://localhost:9443/cas/logout</a>).</p>
                                </li>
                                <li>
                                    <p>On the CAS Server side, the CAS single logout URL then submits single logout requests to all the CAS Services. On the CAS Service side, JASIG`s <code>SingleSignOutFilter</code> processes the logout request by invaliditing the original session.</p>
                                </li>
                            </ul>
                        </div>
                        <div class="paragraph">
                            <p>The next step is to add the following to your web.xml</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;filter&gt;
  &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;
  &lt;filter-class&gt;
    org.springframework.web.filter.CharacterEncodingFilter
  &lt;/filter-class&gt;
  &lt;init-param&gt;
    &lt;param-name&gt;encoding&lt;/param-name&gt;
    &lt;param-value&gt;UTF-8&lt;/param-value&gt;
  &lt;/init-param&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
  &lt;filter-name&gt;characterEncodingFilter&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
&lt;listener&gt;
  &lt;listener-class&gt;
    org.jasig.cas.client.session.SingleSignOutHttpSessionListener
  &lt;/listener-class&gt;
&lt;/listener&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>When using the SingleSignOutFilter you might encounter some encoding issues. Therefore it is recommended to add the <code>CharacterEncodingFilter</code> to ensure that the character encoding is correct when using the <code>SingleSignOutFilter</code>. Again, refer to JASIG`s documentation for details. The <code>SingleSignOutHttpSessionListener</code> ensures that when an <code>HttpSession</code> expires, the mapping used for single logout is removed.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="cas-pt-client"><a class="anchor" href="#cas-pt-client"></a>6.3.3. Authenticating to a Stateless Service with CAS</h4>
                        <div class="paragraph">
                            <p>This section describes how to authenticate to a service using CAS. In other words, this section discusses how to setup a client that uses a service that authenticates with CAS. The next section describes how to setup a stateless service to Authenticate using CAS.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="cas-pt-client-config"><a class="anchor" href="#cas-pt-client-config"></a>Configuring CAS to Obtain Proxy Granting Tickets</h5>
                            <div class="paragraph">
                                <p>In order to authenticate to a stateless service, the application needs to obtain a proxy granting ticket (PGT). This section describes how to configure Spring Security to obtain a PGT building upon thencas-st[Service Ticket Authentication] configuration.</p>
                            </div>
                            <div class="paragraph">
                                <p>The first step is to include a <code>ProxyGrantingTicketStorage</code> in your Spring Security configuration. This is used to store PGT`s that are obtained by the <code>CasAuthenticationFilter</code> so that they can be used to obtain proxy tickets. An example configuration is shown below</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;!--
  NOTE: In a real application you should not use an in
        memory implementation. You will also want to ensure
        to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup()
--&gt;
&lt;bean id="pgtStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"/&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The next step is to update the <code>CasAuthenticationProvider</code> to be able to obtain proxy tickets. To do this replace the <code>Cas20ServiceTicketValidator</code> with a <code>Cas20ProxyTicketValidator</code>. The <code>proxyCallbackUrl</code> should be set to a URL that the application will receive PGT`s at. Last, the configuration should also reference the <code>ProxyGrantingTicketStorage</code> so it can use a PGT to obtain proxy tickets. You can find an example of the configuration changes that should be made below.</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>&lt;bean id="casAuthenticationProvider"
    class="org.springframework.security.cas.authentication.CasAuthenticationProvider"&gt;
  ...
  &lt;property name="ticketValidator"&gt;
    &lt;bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator"&gt;
      &lt;constructor-arg value="https://localhost:9443/cas"/&gt;
        &lt;property name="proxyCallbackUrl"
          value="https://localhost:8443/cas-sample/j_spring_cas_security_proxyreceptor"/&gt;
      &lt;property name="proxyGrantingTicketStorage" ref="pgtStorage"/&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                                </div>
                            </div>
                            <div class="paragraph">
                                <p>The last step is to update the <code>CasAuthenticationFilter</code> to accept PGT and to store them in the <code>ProxyGrantingTicketStorage</code>. It is important the the <code>proxyReceptorUrl</code> matches the <code>proxyCallbackUrl</code> of the <code>Cas20ProxyTicketValidator</code>. An example configuration is shown below.</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>
  &lt;bean id="casFilter"
        class="org.springframework.security.cas.web.CasAuthenticationFilter"&gt;
    ...
    &lt;property name="proxyGrantingTicketStorage" ref="pgtStorage"/&gt;
    &lt;property name="proxyReceptorUrl" value="/j_spring_cas_security_proxyreceptor"/&gt;
  &lt;/bean&gt;
</code></pre>
                                </div>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="cas-pt-client-sample"><a class="anchor" href="#cas-pt-client-sample"></a>Calling a Stateless Service Using a Proxy Ticket</h5>
                            <div class="paragraph">
                                <p>Now that Spring Security obtains PGTs, you can use them to create proxy tickets which can be used to authenticate to a stateless service. The <a href="#cas-sample">CAS sample application</a> contains a working example in the <code>ProxyTicketSampleServlet</code>. Example code can be found below:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint java language-java"><code>protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  // NOTE: The CasAuthenticationToken can also be obtained using
  // SecurityContextHolder.getContext().getAuthentication()
  final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
  // proxyTicket could be reused to make calls to the CAS service even if the
  // target url differs
  final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);

  // Make a remote call using the proxy ticket
  final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
  String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
  ...
}</code></pre>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="cas-pt"><a class="anchor" href="#cas-pt"></a>6.3.4. Proxy Ticket Authentication</h4>
                        <div class="paragraph">
                            <p>The <code>CasAuthenticationProvider</code> distinguishes between stateful and stateless clients. A stateful client is considered any that submits to the <code>filterProcessUrl</code> of the <code>CasAuthenticationFilter</code>. A stateless client is any that presents an authentication request to <code>CasAuthenticationFilter</code> on a URL other than the <code>filterProcessUrl</code>.</p>
                        </div>
                        <div class="paragraph">
                            <p>Because remoting protocols have no way of presenting themselves within the context of an <code>HttpSession</code>, it isn`t possible to rely on the default practice of storing the security context in the session between requests. Furthermore, because the CAS server invalidates a ticket after it has been validated by the <code>TicketValidator</code>, presenting the same proxy ticket on subsequent requests will not work.</p>
                        </div>
                        <div class="paragraph">
                            <p>One obvious option is to not use CAS at all for remoting protocol clients. However, this would eliminate many of the desirable features of CAS. As a middle-ground, the <code>CasAuthenticationProvider</code> uses a <code>StatelessTicketCache</code>. This is used solely for stateless clients which use a principal equal to <code>CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER</code>. What happens is the <code>CasAuthenticationProvider</code> will store the resulting <code>CasAuthenticationToken</code> in the <code>StatelessTicketCache</code>, keyed on the proxy ticket. Accordingly, remoting protocol clients can present the same proxy ticket and the <code>CasAuthenticationProvider</code> will not need to contact the CAS server for validation (aside from the first request). Once authenticated, the proxy ticket could be used for URLs other than the original target service.</p>
                        </div>
                        <div class="paragraph">
                            <p>This section builds upon the previous sections to accomodate proxy ticket authentication. The first step is to specify to authenticate all artifacts as shown below.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="serviceProperties"
      class="org.springframework.security.cas.ServiceProperties"&gt;
  ...
  &lt;property name="authenticateAllArtifacts" value="true"/&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The next step is to specify <code>serviceProperties</code> and the <code>authenticationDetailsSource</code> for the <code>CasAuthenticationFilter</code>. The <code>serviceProperties</code> property instructs the <code>CasAuthenticationFilter</code> to attempt to authenticate all artifacts instead of only ones present on the <code>filterProcessUrl</code>. The <code>ServiceAuthenticationDetailsSource</code> creates a <code>ServiceAuthenticationDetails</code> that ensures the current URL, based upon the <code>HttpServletRequest</code>, is used as the service URL when validating the ticket. The method for generating the service URL can be customized by injecting a custom <code>AuthenticationDetailsSource</code> that returns a custom <code>ServiceAuthenticationDetails</code>.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>&lt;bean id="casFilter"
      class="org.springframework.security.cas.web.CasAuthenticationFilter"&gt;
  ...
  &lt;property name="serviceProperties" ref="serviceProperties"/&gt;
  &lt;property name="authenticationDetailsSource"&gt;
    &lt;bean class=
      "org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"&gt;
      &lt;constructor-arg ref="serviceProperties"/&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You will also need to update the <code>CasAuthenticationProvider</code> to handle proxy tickets. To do this replace the <code>Cas20ServiceTicketValidator</code> with a <code>Cas20ProxyTicketValidator</code>. You will need to configure the <code>statelessTicketCache</code> and which proxies you want to accept. You can find an example of the updates required to accept all proxies below.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint xml language-xml"><code>
&lt;bean id="casAuthenticationProvider"
    class="org.springframework.security.cas.authentication.CasAuthenticationProvider"&gt;
  ...
  &lt;property name="ticketValidator"&gt;
    &lt;bean class="org.jasig.cas.client.validation.Cas20ProxyTicketValidator"&gt;
      &lt;constructor-arg value="https://localhost:9443/cas"/&gt;
      &lt;property name="acceptAnyProxy" value="true"/&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
  &lt;property name="statelessTicketCache"&gt;
    &lt;bean class="org.springframework.security.cas.authentication.EhCacheBasedTicketCache"&gt;
      &lt;property name="cache"&gt;
        &lt;bean class="net.sf.ehcache.Cache"
            init-method="initialise" destroy-method="dispose"&gt;
          &lt;constructor-arg value="casTickets"/&gt;
          &lt;constructor-arg value="50"/&gt;
          &lt;constructor-arg value="true"/&gt;
          &lt;constructor-arg value="false"/&gt;
          &lt;constructor-arg value="3600"/&gt;
          &lt;constructor-arg value="900"/&gt;
        &lt;/bean&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
&lt;/bean&gt;</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="x509"><a class="anchor" href="#x509"></a>7. X.509 Authentication</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="x509-overview"><a class="anchor" href="#x509-overview"></a>7.1. Overview</h3>
                    <div class="paragraph">
                        <p>The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser. The browser will automatically check that the certificate presented by a server has been issued (ie digitally signed) by one of a list of trusted certificate authorities which it maintains.</p>
                    </div>
                    <div class="paragraph">
                        <p>You can also use SSL with "mutual authentication"; the server will then request a valid certificate from the client as part of the SSL handshake. The server will authenticate the client by checking that its certificate is signed by an acceptable authority. If a valid certificate has been provided, it can be obtained through the servlet API in an application. Spring Security X.509 module extracts the certificate using a filter. It maps the certificate to an application user and loads that user`s set of granted authorities for use with the standard Spring Security infrastructure.</p>
                    </div>
                    <div class="paragraph">
                        <p>You should be familiar with using certificates and setting up client authentication for your servlet container before attempting to use it with Spring Security. Most of the work is in creating and installing suitable certificates and keys. For example, if you`re using Tomcat then read the instructions here <a href="http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html">http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html</a>. It`s important that you get this working before trying it out with Spring Security</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="adding-x-509-authentication-to-your-web-application"><a class="anchor" href="#adding-x-509-authentication-to-your-web-application"></a>7.2. Adding X.509 Authentication to Your Web Application</h3>
                    <div class="paragraph">
                        <p>Enabling X.509 client authentication is very straightforward. Just add the <code>&lt;x509/&gt;</code> element to your http security namespace configuration.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;http&gt;
 ...
    &lt;x509 subject-principal-regex="CN=(.*?)," user-service-ref="userService"/&gt;;
&lt;/http&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The element has two optional attributes:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p><code>subject-principal-regex</code>. The regular expression used to extract a username from the certificate`s subject name. The default value is shown above. This is the username which will be passed to the <code>UserDetailsService</code> to load the authorities for the user.</p>
                            </li>
                            <li>
                                <p><code>user-service-ref</code>. This is the bean Id of the <code>UserDetailsService</code> to be used with X.509. It isn`t needed if there is only one defined in your application context.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>The <code>subject-principal-regex</code> should contain a single group. For example the default expression "CN=(.*?)," matches the common name field. So if the subject name in the certificate is "CN=Jimi Hendrix, OU=&#8230;", this will give a user name of "Jimi Hendrix". The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=<a href="mailto:jimi@hendrix.org">jimi@hendrix.org</a>,CN=&#8230;" giving a user name "<a href="mailto:jimi@hendrix.org">jimi@hendrix.org</a>". If the client presents a certificate and a valid username is successfully extracted, then there should be a valid <code>Authentication</code> object in the security context. If no certificate is found, or no corresponding user could be found then the security context will remain empty. This means that you can easily use X.509 authentication with other options such as a form-based login.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="x509-ssl-config"><a class="anchor" href="#x509-ssl-config"></a>7.3. Setting up SSL in Tomcat</h3>
                    <div class="paragraph">
                        <p>There are some pre-generated certificates in the <code>samples/certificate</code> directory in the Spring Security project. You can use these to enable SSL for testing if you don`t want to generate your own. The file <code>server.jks</code> contains the server certificate, private key and the issuing certificate authority certificate. There are also some client certificate files for the users from the sample applications. You can install these in your browser to enable SSL client authentication.</p>
                    </div>
                    <div class="paragraph">
                        <p>To run tomcat with SSL support, drop the <code>server.jks</code> file into the tomcat <code>conf</code> directory and add the following connector to the <code>server.xml</code> file</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" scheme="https" secure="true"
            clientAuth="true" sslProtocol="TLS"
            keystoreFile="${catalina.home}/conf/server.jks"
            keystoreType="JKS" keystorePass="password"
            truststoreFile="${catalina.home}/conf/server.jks"
            truststoreType="JKS" truststorePass="password"
/&gt;
</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p><code>clientAuth</code> can also be set to <code>want</code> if you still want SSL connections to succeed even if the client doesn`t provide a certificate. Clients which don`t present a certificate won`t be able to access any objects secured by Spring Security unless you use a non-X.509 authentication mechanism, such as form authentication.</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="runas"><a class="anchor" href="#runas"></a>8. Run-As Authentication Replacement</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="runas-overview"><a class="anchor" href="#runas-overview"></a>8.1. Overview</h3>
                    <div class="paragraph">
                        <p>The <code>AbstractSecurityInterceptor</code> is able to temporarily replace the <code>Authentication</code> object in the <code>SecurityContext</code> and <code>SecurityContextHolder</code> during the secure object callback phase. This only occurs if the original <code>Authentication</code> object was successfully processed by the <code>AuthenticationManager</code> and <code>AccessDecisionManager</code>. The <code>RunAsManager</code> will indicate the replacement <code>Authentication</code> object, if any, that should be used during the <code>SecurityInterceptorCallback</code>.</p>
                    </div>
                    <div class="paragraph">
                        <p>By temporarily replacing the <code>Authentication</code> object during the secure object callback phase, the secured invocation will be able to call other objects which require different authentication and authorization credentials. It will also be able to perform any internal security checks for specific <code>GrantedAuthority</code> objects. Because Spring Security provides a number of helper classes that automatically configure remoting protocols based on the contents of the <code>SecurityContextHolder</code>, these run-as replacements are particularly useful when calling remote web services</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="runas-config"><a class="anchor" href="#runas-config"></a>8.2. Configuration</h3>
                    <div class="paragraph">
                        <p>A <code>RunAsManager</code> interface is provided by Spring Security:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>Authentication buildRunAs(Authentication authentication, Object object,
    List&lt;ConfigAttribute&gt; config);

boolean supports(ConfigAttribute attribute);

boolean supports(Class clazz);</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The first method returns the <code>Authentication</code> object that should replace the existing <code>Authentication</code> object for the duration of the method invocation. If the method returns <code>null</code>, it indicates no replacement should be made. The second method is used by the <code>AbstractSecurityInterceptor</code> as part of its startup validation of configuration attributes. The <code>supports(Class)</code> method is called by a security interceptor implementation to ensure the configured <code>RunAsManager</code> supports the type of secure object that the security interceptor will present.</p>
                    </div>
                    <div class="paragraph">
                        <p>One concrete implementation of a <code>RunAsManager</code> is provided with Spring Security. The <code>RunAsManagerImpl</code> class returns a replacement <code>RunAsUserToken</code> if any <code>ConfigAttribute</code> starts with <code>RUN_AS_</code>. If any such <code>ConfigAttribute</code> is found, the replacement <code>RunAsUserToken</code> will contain the same principal, credentials and granted authorities as the original <code>Authentication</code> object, along with a new <code>GrantedAuthorityImpl</code> for each <code>RUN_AS_</code> <code>ConfigAttribute</code>. Each new <code>GrantedAuthorityImpl</code> will be prefixed with <code>ROLE_</code>, followed by the <code>RUN_AS</code> <code>ConfigAttribute</code>. For example, a <code>RUN_AS_SERVER</code> will result in the replacement <code>RunAsUserToken</code> containing a <code>ROLE_RUN_AS_SERVER</code> granted authority.</p>
                    </div>
                    <div class="paragraph">
                        <p>The replacement <code>RunAsUserToken</code> is just like any other <code>Authentication</code> object. It needs to be authenticated by the <code>AuthenticationManager</code>, probably via delegation to a suitable <code>AuthenticationProvider</code>. The <code>RunAsImplAuthenticationProvider</code> performs such authentication. It simply accepts as valid any <code>RunAsUserToken</code> presented.</p>
                    </div>
                    <div class="paragraph">
                        <p>To ensure malicious code does not create a <code>RunAsUserToken</code> and present it for guaranteed acceptance by the <code>RunAsImplAuthenticationProvider</code>, the hash of a key is stored in all generated tokens. The <code>RunAsManagerImpl</code> and <code>RunAsImplAuthenticationProvider</code> is created in the bean context with the same key:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>
&lt;bean id="runAsManager"
    class="org.springframework.security.access.intercept.RunAsManagerImpl"&gt;
  &lt;property name="key" value="my_run_as_password"/&gt;
&lt;/bean&gt;

&lt;bean id="runAsAuthenticationProvider"
    class="org.springframework.security.access.intercept.RunAsImplAuthenticationProvider"&gt;
  &lt;property name="key" value="my_run_as_password"/&gt;
&lt;/bean&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>By using the same key, each <code>RunAsUserToken</code> can be validated it was created by an approved <code>RunAsManagerImpl</code>. The <code>RunAsUserToken</code> is immutable after creation for security reasons</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="crypto"><a class="anchor" href="#crypto"></a>9. Spring Security Crypto Module</h2>
            <div class="sectionbody">
                <div class="sect2">
                    <h3 id="spring-security-crypto-introduction"><a class="anchor" href="#spring-security-crypto-introduction"></a>9.1. Introduction</h3>
                    <div class="paragraph">
                        <p>The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-crypto-encryption"><a class="anchor" href="#spring-security-crypto-encryption"></a>9.2. Encryptors</h3>
                    <div class="paragraph">
                        <p>The Encryptors class provides factory methods for constructing symmetric encryptors. Using this class, you can create ByteEncryptors to encrypt data in raw byte[] form. You can also construct TextEncryptors to encrypt text strings. Encryptors are thread safe.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="spring-security-crypto-encryption-bytes"><a class="anchor" href="#spring-security-crypto-encryption-bytes"></a>9.2.1. BytesEncryptor</h4>
                        <div class="paragraph">
                            <p>Use the Encryptors.standard factory method to construct a "standard" BytesEncryptor:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>Encryptors.standard("password", "salt");</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The "standard" encryption method is 256-bit AES using PKCS #5`s PBKDF2 (Password-Based Key Derivation Function #2). This method requires Java 6. The password used to generate the SecretKey should be kept in a secure place and not be shared. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. A 16-byte random initialization vector is also applied so each encrypted message is unique.</p>
                        </div>
                        <div class="paragraph">
                            <p>The provided salt should be in hex-encoded String form, be random, and be at least 8 bytes in length. Such a salt may be generated using a KeyGenerator:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte salt that is then hex-encoded</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="spring-security-crypto-encryption-text"><a class="anchor" href="#spring-security-crypto-encryption-text"></a>9.2.2. TextEncryptor</h4>
                        <div class="paragraph">
                            <p>Use the Encryptors.text factory method to construct a standard TextEncryptor:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>
Encryptors.text("password", "salt");</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>A TextEncryptor uses a standard BytesEncryptor to encrypt text data. Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in the database.</p>
                        </div>
                        <div class="paragraph">
                            <p>Use the Encryptors.queryableText factory method to construct a "queryable" TextEncryptor:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>Encryptors.queryableText("password", "salt");</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The difference between a queryable TextEncryptor and a standard TextEncryptor has to do with initialization vector (iv) handling. The iv used in a queryable TextEncryptor#encrypt operation is shared, or constant, and is not randomly generated. This means the same text encrypted multiple times will always produce the same encryption result. This is less secure, but necessary for encrypted data that needs to be queried against. An example of queryable encrypted text would be an OAuth apiKey.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-crypto-keygenerators"><a class="anchor" href="#spring-security-crypto-keygenerators"></a>9.3. Key Generators</h3>
                    <div class="paragraph">
                        <p>The KeyGenerators class provides a number of convenience factory methods for constructing different types of key generators. Using this class, you can create a BytesKeyGenerator to generate byte[] keys. You can also construct a StringKeyGenerator to generate string keys. KeyGenerators are thread safe.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="byteskeygenerator"><a class="anchor" href="#byteskeygenerator"></a>9.3.1. BytesKeyGenerator</h4>
                        <div class="paragraph">
                            <p>Use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>KeyGenerator generator = KeyGenerators.secureRandom();
byte[] key = generator.generateKey();</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>The default key length is 8 bytes. There is also a KeyGenerators.secureRandom variant that provides control over the key length:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>KeyGenerators.secureRandom(16);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator that always returns the same key on every invocation:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>KeyGenerators.shared(16);</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="stringkeygenerator"><a class="anchor" href="#stringkeygenerator"></a>9.3.2. StringKeyGenerator</h4>
                        <div class="paragraph">
                            <p>Use the KeyGenerators.string factory method to construct a 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String:</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint java language-java"><code>KeyGenerators.string();</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-crypto-passwordencoders"><a class="anchor" href="#spring-security-crypto-passwordencoders"></a>9.4. Password Encoding</h3>
                    <div class="paragraph">
                        <p>The password package of the spring-security-crypto module provides support for encoding passwords. <code>PasswordEncoder</code> is the central service interface and has the following signature:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>public interface PasswordEncoder {

  String encode(String rawPassword);

  boolean matches(String rawPassword, String encodedPassword);
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The matches method returns true if the rawPassword, once encoded, equals the encodedPassword. This method is designed to support password-based authentication schemes.</p>
                    </div>
                    <div class="paragraph">
                        <p>The <code>BCryptPasswordEncoder</code> implementation uses the widely supported "bcrypt" algorithm to hash the passwords. Bcrypt uses a random 16 byte salt value and is a deliberately slow algorithm, in order to hinder password crackers. The amount of work it does can be tuned using the "strength" parameter which takes values from 4 to 31. The higher the value, the more work has to be done to calculate the hash. The default value is 10. You can change this value in your deployed system without affecting existing passwords, as the value is also stored in the encoded hash.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>
// Create an encoder with strength 16
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
String result = encoder.encode("myPassword");
assertTrue(encoder.matches("myPassword", result));</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="concurrency"><a class="anchor" href="#concurrency"></a>10. Concurrency Support</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>In most environments, Security is stored on a per <code>Thread</code> basis. This means that when work is done on a new <code>Thread</code>, the <code>SecurityContext</code> is lost. Spring Security provides some infrastructure to help make this much easier for users. Spring Security provides low level abstractions for working with Spring Security in multi threaded environments. In fact, this is what Spring Security builds on to integration with <a href="#servletapi-start-runnable">AsyncContext.start(Runnable)</a> and <a href="#mvc-async">Spring MVC Async Integration</a>.</p>
                </div>
                <div class="sect2">
                    <h3 id="delegatingsecuritycontextrunnable"><a class="anchor" href="#delegatingsecuritycontextrunnable"></a>10.1. DelegatingSecurityContextRunnable</h3>
                    <div class="paragraph">
                        <p>One of the most fundamental building blocks within Spring Security`s concurrency support is the <code>DelegatingSecurityContextRunnable</code>. It wraps a delegate <code>Runnable</code> in order to initialize the <code>SecurityContextHolder</code> with a specified <code>SecurityContext</code> for the delegate. It then invokes the delegate Runnable ensuring to clear the <code>SecurityContextHolder</code> afterwards. The <code>DelegatingSecurityContextRunnable</code> looks something like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>public void run() {
  try {
    SecurityContextHolder.setContext(securityContext);
    delegate.run();
  } finally {
    SecurityContextHolder.clearContext();
  }
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. For example, you might have used Spring Security`s <a href="#nsa-global-method-security">&lt;global-method-security&gt;</a> support to secure one of your services. You can now easily transfer the <code>SecurityContext</code> of the current <code>Thread</code> to the <code>Thread</code> that invokes the secured service. An example of how you might do this can be found below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>Runnable originalRunnable = new Runnable() {
  public void run() {
    // invoke secured service
  }
};

SecurityContext context = SecurityContextHolder.getContext();
DelegatingSecurityContextRunnable wrappedRunnable =
    new DelegatingSecurityContextRunnable(originalRunnable, context);

new Thread(wrappedRunnable).start();</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The code above performs the following steps:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>Creates a <code>Runnable</code> that will be invoking our secured service. Notice that it is not aware of Spring Security</p>
                            </li>
                            <li>
                                <p>Obtains the <code>SecurityContext</code> that we wish to use from the <code>SecurityContextHolder</code> and initializes the <code>DelegatingSecurityContextRunnable</code></p>
                            </li>
                            <li>
                                <p>Use the <code>DelegatingSecurityContextRunnable</code> to create a Thread</p>
                            </li>
                            <li>
                                <p>Start the Thread we created</p>
                            </li>
                        </ul>
                    </div>
                    <div class="paragraph">
                        <p>Since it is quite common to create a <code>DelegatingSecurityContextRunnable</code> with the <code>SecurityContext</code> from the <code>SecurityContextHolder</code> there is a shortcut constructor for it. The following code is the same as the code above:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>Runnable originalRunnable = new Runnable() {
  public void run() {
    // invoke secured service
  }
};

DelegatingSecurityContextRunnable wrappedRunnable =
    new DelegatingSecurityContextRunnable(originalRunnable);

new Thread(wrappedRunnable).start();</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The code we have is simple to use, but it still requires knowledge that we are using Spring Security. In the next section we will take a look at how we can utilize <code>DelegatingSecurityContextExecutor</code> to hide the fact that we are using Spring Security.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="delegatingsecuritycontextexecutor"><a class="anchor" href="#delegatingsecuritycontextexecutor"></a>10.2. DelegatingSecurityContextExecutor</h3>
                    <div class="paragraph">
                        <p>In the previous section we found that it was easy to use the <code>DelegatingSecurityContextRunnable</code>, but it was not ideal since we had to be aware of Spring Security in order to use it. Let`s take a look at how <code>DelegatingSecurityContextExecutor</code> can shield our code from any knowledge that we are using Spring Security.</p>
                    </div>
                    <div class="paragraph">
                        <p>The design of <code>DelegatingSecurityContextExecutor</code> is very similar to that of <code>DelegatingSecurityContextRunnable</code> except it accepts a delegate <code>Executor</code> instead of a delegate <code>Runnable</code>. You can see an example of how it might be used below:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication =
    new UsernamePasswordAuthenticationToken("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
context.setAuthentication(authentication);

SimpleAsyncTaskExecutor delegateExecutor =
    new SimpleAsyncTaskExecutor();
DelegatingSecurityContextExecutor executor =
    new DelegatingSecurityContextExecutor(delegateExecutor, context);

Runnable originalRunnable = new Runnable() {
  public void run() {
    // invoke secured service
  }
};

executor.execute(originalRunnable);</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>The code performs the following steps:</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>Creates the <code>SecurityContext</code> to be used for our <code>DelegatingSecurityContextExecutor</code>. Note that in this example we simply create the <code>SecurityContext</code> by hand. However, it does not matter where or how we get the <code>SecurityContext</code> (i.e. we could obtain it from the <code>SecurityContextHolder</code> if we wanted).</p>
                            </li>
                            <li>
                                <p>Creates a delegateExecutor that is in charge of executing submitted `Runnable`s</p>
                            </li>
                            <li>
                                <p>Finally we create a <code>DelegatingSecurityContextExecutor</code> which is in charge of wrapping any Runnable that is passed into the execute method with a <code>DelegatingSecurityContextRunnable</code>. It then passes the wrapped Runnable to the delegateExecutor. In this instance, the same <code>SecurityContext</code> will be used for every Runnable submitted to our <code>DelegatingSecurityContextExecutor</code>. This is nice if we are running background tasks that need to be run by a user with elevated privileges.</p>
                            </li>
                            <li>
                                <p>At this point you may be asking yourself "How does this shield my code of any knowledge of Spring Security?" Instead of creating the <code>SecurityContext</code> and the <code>DelegatingSecurityContextExecutor</code> in our own code, we can inject an already initialized instance of <code>DelegatingSecurityContextExecutor</code>.</p>
                            </li>
                        </ul>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@Autowired
private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor

public void submitRunnable() {
  Runnable originalRunnable = new Runnable() {
    public void run() {
      // invoke secured service
    }
  };
  executor.execute(originalRunnable);
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Now our code is unaware that the <code>SecurityContext</code> is being propagated to the <code>Thread</code>, then the <code>originalRunnable</code> is executed, and then the <code>SecurityContextHolder</code> is cleared out. In this example, the same user is being used to execute each Thread. What if we wanted to use the user from <code>SecurityContextHolder</code> at the time we invoked <code>executor.execute(Runnable)</code> (i.e. the currently logged in user) to process <code>originalRunnable</code>? This can be done by removing the <code>SecurityContext</code> argument from our <code>DelegatingSecurityContextExecutor</code> constructor. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor();
DelegatingSecurityContextExecutor executor =
    new DelegatingSecurityContextExecutor(delegateExecutor);</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Now anytime <code>executor.execute(Runnable)</code> is executed the <code>SecurityContext</code> is first obtained by the <code>SecurityContextHolder</code> and then that <code>SecurityContext</code> is used to create our <code>DelegatingSecurityContextRunnable</code>. This means that we are executing our <code>Runnable</code> with the same user that was used to invoke the <code>executor.execute(Runnable)</code> code.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-concurrency-classes"><a class="anchor" href="#spring-security-concurrency-classes"></a>10.3. Spring Security Concurrency Classes</h3>
                    <div class="paragraph">
                        <p>Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. They are quite self explanatory once you understand the previous code.</p>
                    </div>
                    <div class="ulist">
                        <ul>
                            <li>
                                <p>DelegatingSecurityContextCallable</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextExecutor</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextExecutorService</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextRunnable</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextScheduledExecutorService</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextSchedulingTaskExecutor</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextAsyncTaskExecutor</p>
                            </li>
                            <li>
                                <p>DelegatingSecurityContextTaskExecutor</p>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="mvc"><a class="anchor" href="#mvc"></a>11. Spring MVC Integration</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>Spring Security provides a number of optional integrations with Spring MVC. This section covers the integration in further detail.</p>
                </div>
                <div class="sect2">
                    <h3 id="mvc-enablewebmvcsecurity"><a class="anchor" href="#mvc-enablewebmvcsecurity"></a>11.1. @EnableWebMvcSecurity</h3>
                    <div class="paragraph">
                        <p>To enable Spring Security integration with Spring MVC add the <code>@EnableWebMvcSecurity</code> annotation to your configuration. A typical example will look something like this:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@Configuration
@EnableWebMvcSecurity
public class SecurityConfig {
    // ...
}</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="mvc-authentication-principal"><a class="anchor" href="#mvc-authentication-principal"></a>11.2. @AuthenticationPrincipal</h3>
                    <div class="paragraph">
                        <p>Spring Security provides <code>AuthenticationPrincipalArgumentResolver</code> which can automatically resolve the current <code>Authentication.getPrincipal()</code> for Spring MVC arguments. By using <a href="#mvc-enablewebmvcsecurity">@EnableWebMvcSecurity</a> you will automatically have this added to your Spring MVC configuration. If you use XML based configuraiton, you must add this yourself.</p>
                    </div>
                    <div class="paragraph">
                        <p>Once <code>AuthenticationPrincipalArgumentResolver</code> is properly configured, you can be entirely decoupled from Spring Security in your Spring MVC layer.</p>
                    </div>
                    <div class="paragraph">
                        <p>Consider a situation where a custom <code>UserDetailsService</code> that returns an <code>Object</code> that implements <code>UserDetails</code> and your own <code>CustomUser</code> <code>Object</code>. The <code>CustomUser</code> of the currently authenticated user could be accessed using the following code:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;

// ...

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser() {
    Authentication authentication =
      SecurityContextHolder.getContext().getAuthentication();
    CustomUser custom = (CustomUser) authentication == null ? null : authentication.getPrincipal();

    // .. find messags for this user and return them ...
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>As of Spring Security 3.2 we can resolve the argument more directly by adding an annotation. For example:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser customUser) {

    // .. find messags for this user and return them ...
}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>We can further remove our dependency on Spring Security by making <code>@AuthenticationPrincipal</code> a meta annotation on our own annotation. Below we demonstrate how we could do this on an annotation named <code>@CurrentUser</code>.</p>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    It is important to realize that in order to remove the dependency on Spring Security, it is the consuming application that would create <code>@CurrentUser</code>. This step is not strictly required, but assists in isolating your dependency to Spring Security to a more central location.
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Now that <code>@CurrentUser</code> has been specified, we can use it to signal to resolve our <code>CustomUser</code> of the currently authenticated user. We have also isolated our dependency on Spring Security to a single file.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@CurrentUser CustomUser customUser) {

    // .. find messags for this user and return them ...
}</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="mvc-async"><a class="anchor" href="#mvc-async"></a>11.3. Spring MVC Async Integration</h3>
                    <div class="paragraph">
                        <p>Spring Web MVC 3.2+ has excellent support for <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async">Asynchronous Request Processing</a>. With no additional configuration, Spring Security will automatically setup the <code>SecurityContext</code> to the <code>Thread</code> that executes a <code>Callable</code> returned by your controllers. For example, the following method will automatically have its <code>Callable</code> executed with the <code>SecurityContext</code> that was available when the <code>Callable</code> was created:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint java language-java"><code>@RequestMapping(method=RequestMethod.POST)
public Callable&lt;String&gt; processUpload(final MultipartFile file) {

  return new Callable&lt;String&gt;() {
    public Object call() throws Exception {
      // ...
      return "someView";
    }
  };
}</code></pre>
                        </div>
                    </div>
                    <div class="admonitionblock note">
                        <table>
                            <tr>
                                <td class="icon">
                                    <i class="icon-note" title="Note"></i>
                                </td>
                                <td class="content">
                                    <div class="title">Associating SecurityContext to Callable`s</div>
                                    <div class="paragraph">
                                        <p>More technically speaking, Spring Security integrates with <code>WebAsyncManager</code>. The <code>SecurityContext</code> that is used to process the <code>Callable</code> is the <code>SecurityContext</code> that exists on the <code>SecurityContextHolder</code> at the time <code>startCallableProcessing</code> is invoked.</p>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="paragraph">
                        <p>There is no automatic integration with a <code>DeferredResult</code> that is returned by controllers. This is because <code>DeferredResult</code> is processed by the users and thus there is no way of automatically integrating with it. However, you can still use <a href="#concurrency">Concurrency Support</a> to provide transparent integration with Spring Security.</p>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="mvc-csrf"><a class="anchor" href="#mvc-csrf"></a>11.4. Spring MVC and CSRF Integration</h3>
                    <div class="paragraph">
                        <p>Spring Security will automatically <a href="#csrf-include-csrf-token">include the CSRF Token</a> within forms that use the <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag">Spring MVC form tag</a>. For example, the following JSP:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:form="http://www.springframework.org/tags/form" version="2.0"&gt;
    &lt;jsp:directive.page language="java" contentType="text/html" /&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt;
    &lt;!-- ... --&gt;

    &lt;c:url var="logoutUrl" value="/logout"/&gt;
    &lt;form:form action="${logoutUrl}"
        method="post"&gt;
      &lt;input type="submit"
        value="Log out" /&gt;
      &lt;input type="hidden"
        name="${_csrf.parameterName}"
        value="${_csrf.token}"/&gt;
    &lt;/form:form&gt;

    &lt;!-- ... --&gt;
&lt;/html&gt;
&lt;/jsp:root&gt;</code></pre>
                        </div>
                    </div>
                    <div class="paragraph">
                        <p>Will output HTML that is similar to the following:</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint xml language-xml"><code>&lt;!-- ... --&gt;

&lt;form action="/context/logout" method="post"&gt;
  &lt;input type="submit" value="Log out"/&gt;
  &lt;input type="hidden" name="_csrf" value="f81d4fae-7dec-11d0-a765-00a0c91e6bf6"/&gt;
&lt;/form&gt;

&lt;!-- ... --&gt;</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <h1 id="appendix" class="sect0"><a class="anchor" href="#appendix"></a>Appendix</h1>
        <div class="sect1">
            <h2 id="appendix-schema"><a class="anchor" href="#appendix-schema"></a>1. Security Database Schema</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>There are various database schema used by the framework and this appendix provides a single reference point to them all. You only need to provide the tables for the areas of functonality you require.</p>
                </div>
                <div class="paragraph">
                    <p>DDL statements are given for the HSQLDB database. You can use these as a guideline for defining the schema for the database you are using.</p>
                </div>
                <div class="sect2">
                    <h3 id="user-schema"><a class="anchor" href="#user-schema"></a>1.1. User Schema</h3>
                    <div class="paragraph">
                        <p>The standard JDBC implementation of the <code>UserDetailsService</code> (<code>JdbcDaoImpl</code>) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. You will need to adjust this schema to match the database dialect you are using.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint"><code>
create table users(
    username varchar_ignorecase(50) not null primary key,
    password varchar_ignorecase(50) not null,
    enabled boolean not null
);

create table authorities (
    username varchar_ignorecase(50) not null,
    authority varchar_ignorecase(50) not null,
    constraint fk_authorities_users foreign key(username) references users(username)
);
create unique index ix_auth_username on authorities (username,authority);</code></pre>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="group-authorities"><a class="anchor" href="#group-authorities"></a>1.1.1. Group Authorities</h4>
                        <div class="paragraph">
                            <p>Spring Security 2.0 introduced support for group authorities in <code>JdbcDaoImpl</code>. The table structure if groups are enabled is as follows. You will need to adjust this schema to match the database dialect you are using.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint"><code>
create table groups (
    id bigint generated by default as identity(start with 0) primary key,
    group_name varchar_ignorecase(50) not null
);

create table group_authorities (
    group_id bigint not null,
    authority varchar(50) not null,
    constraint fk_group_authorities_group foreign key(group_id) references groups(id)
);

create table group_members (
    id bigint generated by default as identity(start with 0) primary key,
    username varchar(50) not null,
    group_id bigint not null,
    constraint fk_group_members_group foreign key(group_id) references groups(id)
);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>Remember that these tables are only required if you are using the provided JDBC <code>UserDetailsService</code> implementation. If you write your own or choose to implement <code>AuthenticationProvider</code> without a <code>UserDetailsService</code>, then you have complete freedom over how you store the data, as long as the interface contract is satisfied.</p>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="persistent-login-remember-me-schema"><a class="anchor" href="#persistent-login-remember-me-schema"></a>1.2. Persistent Login (Remember-Me) Schema</h3>
                    <div class="paragraph">
                        <p>This table is used to store data used by the more secure <a href="#remember-me-persistent-token">persistent token</a> remember-me implementation. If you are using <code>JdbcTokenRepositoryImpl</code> either directly or through the namespace, then you will need this table. Remember to adjust this schema to match the database dialect you are using.</p>
                    </div>
                    <div class="listingblock">
                        <div class="content">
                            <pre class="prettyprint"><code>
create table persistent_logins (
    username varchar(64) not null,
    series varchar(64) primary key,
    token varchar(64) not null,
    last_used timestamp not null
);
</code></pre>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="dbschema-acl"><a class="anchor" href="#dbschema-acl"></a>1.3. ACL Schema</h3>
                    <div class="paragraph">
                        <p>There are four tables used by the Spring Security <a href="#domain-acls">ACL</a> implementation.</p>
                    </div>
                    <div class="olist arabic">
                        <ol class="arabic">
                            <li>
                                <p><code>acl_sid</code> stores the security identities recognised by the ACL system. These can be unique principals or authorities which may apply to multiple principals.</p>
                            </li>
                            <li>
                                <p><code>acl_class</code> defines the domain object types to which ACLs apply. The <code>class</code> column stores the Java class name of the object.</p>
                            </li>
                            <li>
                                <p><code>acl_object_identity</code> stores the object identity definitions of specific domai objects.</p>
                            </li>
                            <li>
                                <p><code>acl_entry</code> stores the ACL permissions which apply to a specific object identity and security identity.</p>
                            </li>
                        </ol>
                    </div>
                    <div class="paragraph">
                        <p>It is assumed that the database will auto-generate the primary keys for each of the identities. The <code>JdbcMutableAclService</code> has to be able to retrieve these when it has created a new row in the <code>acl_sid</code> or <code>acl_class</code> tables. It has two properties which define the SQL needed to retrieve these values <code>classIdentityQuery</code> and <code>sidIdentityQuery</code>. Both of these default to <code>call identity()</code></p>
                    </div>
                    <div class="paragraph">
                        <p>The ACL artifact JAR contains files for creating the ACL schema in HyperSQL (HSQLDB), PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and Oracle Database. These schemas are also demonstrated in the following sections.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="hypersql"><a class="anchor" href="#hypersql"></a>1.3.1. HyperSQL</h4>
                        <div class="paragraph">
                            <p>The default schema works with the embedded HSQLDB database that is used in unit tests within the framework.</p>
                        </div>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint ddl language-ddl"><code>
create table acl_sid(
    id bigint generated by default as identity(start with 100) not null primary key,
    principal boolean not null,
    sid varchar_ignorecase(100) not null,
    constraint unique_uk_1 unique(sid,principal)
);

create table acl_class(
    id bigint generated by default as identity(start with 100) not null primary key,
    class varchar_ignorecase(100) not null,
    constraint unique_uk_2 unique(class)
);

create table acl_object_identity(
    id bigint generated by default as identity(start with 100) not null primary key,
    object_id_class bigint not null,
    object_id_identity bigint not null,
    parent_object bigint,
    owner_sid bigint,
    entries_inheriting boolean not null,
    constraint unique_uk_3 unique(object_id_class,object_id_identity),
    constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id),
    constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id),
    constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id)
);

create table acl_entry(
    id bigint generated by default as identity(start with 100) not null primary key,
    acl_object_identity bigint not null,
    ace_order int not null,
    sid bigint not null,
    mask integer not null,
    granting boolean not null,
    audit_success boolean not null,
    audit_failure boolean not null,
    constraint unique_uk_4 unique(acl_object_identity,ace_order),
    constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id),
    constraint foreign_fk_5 foreign key(sid) references acl_sid(id)
);</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="postgresql"><a class="anchor" href="#postgresql"></a>1.3.2. PostgreSQL</h4>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint ddl language-ddl"><code>create table acl_sid(
    id bigserial not null primary key,
    principal boolean not null,
    sid varchar(100) not null,
    constraint unique_uk_1 unique(sid,principal)
);

create table acl_class(
    id bigserial not null primary key,
    class varchar(100) not null,
    constraint unique_uk_2 unique(class)
);

create table acl_object_identity(
    id bigserial primary key,
    object_id_class bigint not null,
    object_id_identity bigint not null,
    parent_object bigint,
    owner_sid bigint,
    entries_inheriting boolean not null,
    constraint unique_uk_3 unique(object_id_class,object_id_identity),
    constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id),
    constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id),
    constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id)
);

create table acl_entry(
    id bigserial primary key,
    acl_object_identity bigint not null,
    ace_order int not null,
    sid bigint not null,
    mask integer not null,
    granting boolean not null,
    audit_success boolean not null,
    audit_failure boolean not null,
    constraint unique_uk_4 unique(acl_object_identity,ace_order),
    constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id),
    constraint foreign_fk_5 foreign key(sid) references acl_sid(id)
);</code></pre>
                            </div>
                        </div>
                        <div class="paragraph">
                            <p>You will have to set the <code>classIdentityQuery</code> and <code>sidIdentityQuery</code> properties of <code>JdbcMutableAclService</code> to the following values, respectively:</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><code>select currval(pg_get_serial_sequence('acl_class', 'id'))</code></p>
                                </li>
                                <li>
                                    <p><code>select currval(pg_get_serial_sequence('acl_sid', 'id'))</code></p>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="mysql-and-mariadb"><a class="anchor" href="#mysql-and-mariadb"></a>1.3.3. MySQL and MariaDB</h4>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint ddl language-ddl"><code>CREATE TABLE acl_sid (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    principal BOOLEAN NOT NULL,
    sid VARCHAR(100) NOT NULL,
    UNIQUE KEY unique_acl_sid (sid, principal)
) ENGINE=InnoDB;

CREATE TABLE acl_class (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    class VARCHAR(100) NOT NULL,
    UNIQUE KEY uk_acl_class (class)
) ENGINE=InnoDB;

CREATE TABLE acl_object_identity (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    object_id_class BIGINT UNSIGNED NOT NULL,
    object_id_identity BIGINT NOT NULL,
    parent_object BIGINT UNSIGNED,
    owner_sid BIGINT UNSIGNED,
    entries_inheriting BOOLEAN NOT NULL,
    UNIQUE KEY uk_acl_object_identity (object_id_class, object_id_identity),
    CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id),
    CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id)
) ENGINE=InnoDB;

CREATE TABLE acl_entry (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    acl_object_identity BIGINT UNSIGNED NOT NULL,
    ace_order INTEGER NOT NULL,
    sid BIGINT UNSIGNED NOT NULL,
    mask INTEGER UNSIGNED NOT NULL,
    granting BOOLEAN NOT NULL,
    audit_success BOOLEAN NOT NULL,
    audit_failure BOOLEAN NOT NULL,
    UNIQUE KEY unique_acl_entry (acl_object_identity, ace_order),
    CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id)
) ENGINE=InnoDB;</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="microsoft-sql-server"><a class="anchor" href="#microsoft-sql-server"></a>1.3.4. Microsoft SQL Server</h4>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint ddl language-ddl"><code>CREATE TABLE acl_sid (
    id BIGINT NOT NULL IDENTITY PRIMARY KEY,
    principal BIT NOT NULL,
    sid VARCHAR(100) NOT NULL,
    CONSTRAINT unique_acl_sid UNIQUE (sid, principal)
);

CREATE TABLE acl_class (
    id BIGINT NOT NULL IDENTITY PRIMARY KEY,
    class VARCHAR(100) NOT NULL,
    CONSTRAINT uk_acl_class UNIQUE (class)
);

CREATE TABLE acl_object_identity (
    id BIGINT NOT NULL IDENTITY PRIMARY KEY,
    object_id_class BIGINT NOT NULL,
    object_id_identity BIGINT NOT NULL,
    parent_object BIGINT,
    owner_sid BIGINT,
    entries_inheriting BIT NOT NULL,
    CONSTRAINT uk_acl_object_identity UNIQUE (object_id_class, object_id_identity),
    CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id),
    CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id)
);

CREATE TABLE acl_entry (
    id BIGINT NOT NULL IDENTITY PRIMARY KEY,
    acl_object_identity BIGINT NOT NULL,
    ace_order INTEGER NOT NULL,
    sid BIGINT NOT NULL,
    mask INTEGER NOT NULL,
    granting BIT NOT NULL,
    audit_success BIT NOT NULL,
    audit_failure BIT NOT NULL,
    CONSTRAINT unique_acl_entry UNIQUE (acl_object_identity, ace_order),
    CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id)
);</code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="oracle-database"><a class="anchor" href="#oracle-database"></a>1.3.5. Oracle Database</h4>
                        <div class="listingblock">
                            <div class="content">
                                <pre class="prettyprint ddl language-ddl"><code>CREATE TABLE acl_sid (
    id NUMBER(38) NOT NULL PRIMARY KEY,
    principal NUMBER(1) NOT NULL CHECK (principal in (0, 1)),
    sid NVARCHAR2(100) NOT NULL,
    CONSTRAINT unique_acl_sid UNIQUE (sid, principal)
);
CREATE SEQUENCE acl_sid_sequence START WITH 1 INCREMENT BY 1 NOMAXVALUE;
CREATE OR REPLACE TRIGGER acl_sid_id_trigger
    BEFORE INSERT ON acl_sid
    FOR EACH ROW
BEGIN
    SELECT acl_sid_sequence.nextval INTO :new.id FROM dual;
END;

CREATE TABLE acl_class (
    id NUMBER(38) NOT NULL PRIMARY KEY,
    class NVARCHAR2(100) NOT NULL,
    CONSTRAINT uk_acl_class UNIQUE (class)
);
CREATE SEQUENCE acl_class_sequence START WITH 1 INCREMENT BY 1 NOMAXVALUE;
CREATE OR REPLACE TRIGGER acl_class_id_trigger
    BEFORE INSERT ON acl_class
    FOR EACH ROW
BEGIN
    SELECT acl_class_sequence.nextval INTO :new.id FROM dual;
END;

CREATE TABLE acl_object_identity (
    id NUMBER(38) NOT NULL PRIMARY KEY,
    object_id_class NUMBER(38) NOT NULL,
    object_id_identity NUMBER(38) NOT NULL,
    parent_object NUMBER(38),
    owner_sid NUMBER(38),
    entries_inheriting NUMBER(1) NOT NULL CHECK (entries_inheriting in (0, 1)),
    CONSTRAINT uk_acl_object_identity UNIQUE (object_id_class, object_id_identity),
    CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_object_identity_class FOREIGN KEY (object_id_class) REFERENCES acl_class (id),
    CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY (owner_sid) REFERENCES acl_sid (id)
);
CREATE SEQUENCE acl_object_identity_sequence START WITH 1 INCREMENT BY 1 NOMAXVALUE;
CREATE OR REPLACE TRIGGER acl_object_identity_id_trigger
    BEFORE INSERT ON acl_object_identity
    FOR EACH ROW
BEGIN
    SELECT acl_object_identity_sequence.nextval INTO :new.id FROM dual;
END;

CREATE TABLE acl_entry (
    id NUMBER(38) NOT NULL PRIMARY KEY,
    acl_object_identity NUMBER(38) NOT NULL,
    ace_order INTEGER NOT NULL,
    sid NUMBER(38) NOT NULL,
    mask INTEGER NOT NULL,
    granting NUMBER(1) NOT NULL CHECK (granting in (0, 1)),
    audit_success NUMBER(1) NOT NULL CHECK (audit_success in (0, 1)),
    audit_failure NUMBER(1) NOT NULL CHECK (audit_failure in (0, 1)),
    CONSTRAINT unique_acl_entry UNIQUE (acl_object_identity, ace_order),
    CONSTRAINT fk_acl_entry_object FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity (id),
    CONSTRAINT fk_acl_entry_acl FOREIGN KEY (sid) REFERENCES acl_sid (id)
);
CREATE SEQUENCE acl_entry_sequence START WITH 1 INCREMENT BY 1 NOMAXVALUE;
CREATE OR REPLACE TRIGGER acl_entry_id_trigger
    BEFORE INSERT ON acl_entry
    FOR EACH ROW
BEGIN
    SELECT acl_entry_sequence.nextval INTO :new.id FROM dual;
END;</code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="appendix-namespace"><a class="anchor" href="#appendix-namespace"></a>2. The Security Namespace</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). If you haven`t used the namespace before, please read the <a href="#ns-config">introductory chapter</a> on namespace configuration, as this is intended as a supplement to the information there. Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. The namespace is written in <a href="http://www.relaxng.org/">RELAX NG</a> Compact format and later converted into an XSD schema. If you are familiar with this format, you may wish to examine the <a href="https://fisheye.springsource.org/browse/spring-security/config/src/main/resources/org/springframework/security/config/spring-security-3.2.rnc">schema file</a> directly.</p>
                </div>
                <div class="sect2">
                    <h3 id="nsa-web"><a class="anchor" href="#nsa-web"></a>2.1. Web Application Security</h3>
                    <div class="sect3">
                        <h4 id="nsa-debug"><a class="anchor" href="#nsa-debug"></a>2.1.1. &lt;debug&gt;</h4>
                        <div class="paragraph">
                            <p>Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.</p>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-http"><a class="anchor" href="#nsa-http"></a>2.1.2. &lt;http&gt;</h4>
                        <div class="paragraph">
                            <p>If you use an <code>&lt;http&gt;</code> element within your application, a <code>FilterChainProxy</code> bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain within
                                <code>FilterChainProxy</code>. As of Spring Security 3.1, additional <code>http</code> elements can be used to add extra filter chains <span class="footnote">[<a id="_footnoteref_24" class="footnote" href="#_footnote_24" title="View footnote.">24</a>]</span>. Some core filters are always created in a filter chain and others will be added to the stack depending on the attributes and child elements which are present. The positions of the standard filters are fixed (see
                                <a href="#filter-stack">the filter order table</a> in the namespace introduction), removing a common source of errors with previous versions of the framework when users had to configure the filter chain explicitly in the
                                <code>FilterChainProxy</code> bean. You can, of course, still do this if you need full control of the configuration.</p>
                        </div>
                        <div class="paragraph">
                            <p>All filters which require a reference to the <code>AuthenticationManager</code> will be automatically injected with the internal instance created by the namespace configuration (see the <a href="#ns-auth-manager">introductory chapter</a> for more on the <code>AuthenticationManager</code>).</p>
                        </div>
                        <div class="paragraph">
                            <p>Each <code>&lt;http&gt;</code> namespace block always creates an <code>SecurityContextPersistenceFilter</code>, an <code>ExceptionTranslationFilter</code> and a <code>FilterSecurityInterceptor</code>. These are fixed and cannot be replaced with alternatives.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-http-attributes"><a class="anchor" href="#nsa-http-attributes"></a>&lt;http&gt; Attributes</h5>
                            <div class="paragraph">
                                <p>The attributes on the <code>&lt;http&gt;</code> element control some of the properties on the core filters.</p>
                            </div>
                            <div id="nsa-http-access-decision-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access-decision-manager-ref</strong> Optional attribute specifying the ID of the <code>AccessDecisionManager</code> implementation which should be used for authorizing HTTP requests. By default an <code>AffirmativeBased</code> implementation is used for with a <code>RoleVoter</code> and an <code>AuthenticatedVoter</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-access-denied-page" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access-denied-page</strong> Deprecated in favour of the <a href="#nsa-access-denied-handler">access-denied-handler</a> child element.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-authentication-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-manager-ref</strong> A reference to the <code>AuthenticationManager</code> used for the <code>FilterChain</code> created by this http element.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-auto-config" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>auto-config</strong> Automatically registers a login form, BASIC authentication, logout services. If set to "true", all of these capabilities are added (although you can still customize the configuration of each by providing the respective element). If unspecified, defaults to "false". Use of this attribute is not recommended. Use explicit configuration elements instead to avoid confusion.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-create-session" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>create-session</strong> Controls the eagerness with which an HTTP session is created by Spring Security classes. Options include:</p>
                                        <div class="ulist">
                                            <ul>
                                                <li>
                                                    <p><code>always</code> - Spring Security will proactively create a session if one does not exist.</p>
                                                </li>
                                                <li>
                                                    <p><code>ifRequired</code> - Spring Security will only create a session only if one is required (default value).</p>
                                                </li>
                                                <li>
                                                    <p><code>never</code> - Spring Security will never create a session, but will make use of one if the application does.</p>
                                                </li>
                                                <li>
                                                    <p><code>stateless</code> - Spring Security will not create a session and ignore the session for obtaining a Spring <code>Authentication</code>.</p>
                                                </li>
                                            </ul>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-disable-url-rewriting" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>disable-url-rewriting</strong> Prevents session IDs from being appended to URLs in the application. Clients must use cookies if this attribute is set to <code>true</code>. The default is <code>false</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-entry-point-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>entry-point-ref</strong> Normally the <code>AuthenticationEntryPoint</code> used will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customized <code>AuthenticationEntryPoint</code> bean which will start the authentication process.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-jaas-api-provision" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>jaas-api-provision</strong> If available, runs the request as the <code>Subject</code> acquired from the <code>JaasAuthenticationToken</code> which is implemented by adding a <code>JaasApiIntegrationFilter</code> bean to the stack. Defaults to <code>false</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-name" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>name</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-once-per-request" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>once-per-request</strong> Corresponds to the <code>observeOncePerRequest</code> property of <code>FilterSecurityInterceptor</code>. Defaults to <code>true</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-path-type" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>path-type</strong> Deprecated in favor of <a href="#nsa-http-request-matcher">request-matcher</a>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-pattern" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>pattern</strong> Defining a pattern for the <a href="#nsa-http">http</a> element controls the requests which will be filtered through the list of filters which it defines. The interpretation is dependent on the configured <a href="#nsa-http-request-matcher">request-matcher</a>. If no pattern is defined, all requests will be matched, so the most specific patterns should be declared first.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-realm" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>realm</strong> Sets the realm name used for basic authentication (if enabled). Corresponds to the <code>realmName</code> property on <code>BasicAuthenticationEntryPoint</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-request-matcher" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher</strong> Defines the <code>RequestMatcher</code> strategy used in the <code>FilterChainProxy</code> and the beans created by the <code>intercept-url</code> to match incoming requests. Options are currently <code>ant</code>, <code>regex</code> and <code>ciRegex</code>, for ant, regular-expression and case-insensitive regular-expression repsectively. A separate instance is created for each<a href="#nsa-intercept-url">intercept-url</a> element using its <a href="#nsa-intercept-url-pattern">pattern</a> and <a href="#nsa-intercept-url-method">method</a> attributes. Ant paths are matched using an <code>AntPathRequestMatcher</code> and regular expressions are matched using a <code>RegexRequestMatcher</code>. See the Javadoc for these classes for more details on exactly how the matching is preformed. Ant paths are the default strategy.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-request-matcher-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher-ref</strong> A referenece to a bean that implements <code>RequestMatcher</code> that will determine if this <code>FilterChain</code> should be used. This is a more powerful alternative to <a href="#nsa-http-pattern">pattern</a>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-security" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>security</strong> A request pattern can be mapped to an empty filter chain, by setting this attribute to <code>none</code>. No security will be applied and none of Spring Security`s features will be available.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-security-context-repository-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>security-context-repository-ref</strong> Allows injection of a custom <code>SecurityContextRepository</code> into the <code>SecurityContextPersistenceFilter</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-servlet-api-provision" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>servlet-api-provision</strong> Provides versions of <code>HttpServletRequest</code> security methods such as <code>isUserInRole()</code> and <code>getPrincipal()</code> which are implemented by adding a <code>SecurityContextHolderAwareRequestFilter</code> bean to the stack. Defaults to <code>true</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-use-expressions" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>use-expressions</strong> Enables EL-expressions in the <code>access</code> attribute, as described in the chapter on <a href="#el-access-web">expression-based access-control</a>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-http-children"><a class="anchor" href="#nsa-http-children"></a>Child Elements of &lt;http&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-access-denied-handler">access-denied-handler</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-anonymous">anonymous</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-csrf">csrf</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-custom-filter">custom-filter</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-expression-handler">expression-handler</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-form-login">form-login</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-http-basic">http-basic</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-intercept-url">intercept-url</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-jee">jee</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-logout">logout</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-openid-login">openid-login</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-port-mappings">port-mappings</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-remember-me">remember-me</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-request-cache">request-cache</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-session-management">session-management</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-x509">x509</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-access-denied-handler"><a class="anchor" href="#nsa-access-denied-handler"></a>2.1.3. &lt;access-denied-handler&gt;</h4>
                        <div class="paragraph">
                            <p>This element allows you to set the <code>errorPage</code> property for the default <code>AccessDeniedHandler</code> used by the <code>ExceptionTranslationFilter</code>, using the <a href="#nsa-access-denied-handler-error-page">error-page</a> attribute, or to supply your own implementation using the<a href="#nsa-access-denied-handler-ref">ref</a> attribute. This is discussed in more detail in the section on the <a href="#access-denied-handler">ExceptionTranslationFilter</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-access-denied-handler-parents"><a class="anchor" href="#nsa-access-denied-handler-parents"></a>Parent Elements of &lt;access-denied-handler&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-access-denied-handler-attributes"><a class="anchor" href="#nsa-access-denied-handler-attributes"></a>&lt;access-denied-handler&gt; Attributes</h5>
                            <div id="nsa-access-denied-handler-error-page" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>error-page</strong> The access denied page that an authenticated user will be redirected to if they request a page which they don`t have the authority to access.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-access-denied-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean of type `AccessDeniedHandler `.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-headers"><a class="anchor" href="#nsa-headers"></a>2.1.4. &lt;headers&gt;</h4>
                        <div class="paragraph">
                            <p>This element allows for configuring additional (security) headers to be send with the response. It enables easy configuration for several headers and also allows for setting custom headers through the <a href="#nsa-header">header</a> element. Additional information, can be found in the <a href="#headers">Security Headers</a> section of the reference.</p>
                        </div>
                        <div class="ulist">
                            <ul>
                                <li>
                                    <p><code>Cache-Control</code>, <code>Pragma</code>, and <code>Expires</code> - Can be set using the <a href="#nsa-cache-control">cache-control</a> element. This ensures that the browser does not cache your secured pages.</p>
                                </li>
                                <li>
                                    <p><code>Strict-Transport-Security</code> - Can be set using the <a href="#nsa-hsts">hsts</a> element. This ensures that the browser automatically requests HTTPS for future requests.</p>
                                </li>
                                <li>
                                    <p><code>X-Frame-Options</code> - Can be set using the <a href="#nsa-frame-options">frame-options</a> element. The <a href="http://en.wikipedia.org/wiki/Clickjacking#X-Frame-Options">X-Frame-Options </a> header can be used to prevent clickjacking attacks.</p>
                                </li>
                                <li>
                                    <p><code>X-XSS-Protection</code> - Can be set using the <a href="#nsa-xss-protection">xss-protection</a> element. The <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">X-XSS-Protection </a> header can be used by browser to do basic control.</p>
                                </li>
                                <li>
                                    <p><code>X-Content-Type-Options</code> - Can be set using the <a href="#nsa-content-type-options">content-type-options</a> element. The <a href="http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx">X-Content-Type-Options</a> header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.</p>
                                </li>
                            </ul>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-headers-parents"><a class="anchor" href="#nsa-headers-parents"></a>Parent Elements of &lt;headers&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-headers-children"><a class="anchor" href="#nsa-headers-children"></a>Child Elements of &lt;headers&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-cache-control">cache-control</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-content-type-options">content-type-options</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-frame-options">frame-options</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-header">header</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-hsts">hsts</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-xss-protection">xss-protection</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-cache-control"><a class="anchor" href="#nsa-cache-control"></a>2.1.5. &lt;cache-control&gt;</h4>
                        <div class="paragraph">
                            <p>Adds <code>Cache-Control</code>, <code>Pragma</code>, and <code>Expires</code> headers to ensure that the browser does not cache your secured pages.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-cache-control-parents"><a class="anchor" href="#nsa-cache-control-parents"></a>Parent Elements of &lt;cache-control&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-hsts"><a class="anchor" href="#nsa-hsts"></a>2.1.6. &lt;hsts&gt;</h4>
                        <div class="paragraph">
                            <p>When enabled adds the <a href="http://tools.ietf.org/html/rfc6797">Strict-Transport-Security</a> header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-hsts-attributes"><a class="anchor" href="#nsa-hsts-attributes"></a>&lt;hsts&gt; Attributes</h5>
                            <div id="nsa-hsts-include-subdomains" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>include-sub-domains</strong> Specifies if subdomains should be included. Default true.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-hsts-max-age-seconds" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>max-age-seconds</strong> Specifies the maximum ammount of time the host should be considered a Known HSTS Host. Default one year.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-hsts-request-matcher-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher-ref</strong> The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-hsts-parents"><a class="anchor" href="#nsa-hsts-parents"></a>Parent Elements of &lt;hsts&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-frame-options"><a class="anchor" href="#nsa-frame-options"></a>2.1.7. &lt;frame-options&gt;</h4>
                        <div class="paragraph">
                            <p>When enabled adds the <a href="http://tools.ietf.org/html/draft-ietf-websec-x-frame-options">X-Frame-Options header</a> to the response, this allows newer browsers to do some security checks and prevent <a href="http://en.wikipedia.org/wiki/Clickjacking">clickjacking</a> attacks.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-frame-options-attributes"><a class="anchor" href="#nsa-frame-options-attributes"></a>&lt;frame-options&gt; Attributes</h5>
                            <div id="nsa-frame-options-policy" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>policy</strong></p>
                                        <div class="ulist">
                                            <ul>
                                                <li>
                                                    <p><code>DENY</code> The page cannot be displayed in a frame, regardless of the site attempting to do so. This is the default when frame-options-policy is specified.</p>
                                                </li>
                                                <li>
                                                    <p><code>SAMEORIGIN</code> The page can only be displayed in a frame on the same origin as the page itself</p>
                                                </li>
                                                <li>
                                                    <p><code>ALLOW-FROM</code> <a href="#nsa-frame-options-origin">origin</a> The page can only be displayed in a frame on the specified origin.</p>
                                                </li>
                                            </ul>
                                        </div>
                                        <div class="paragraph">
                                            <p>In other words, if you specify DENY, not only will attempts to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. On the other hand, if you specify SAMEORIGIN, you can still use the page in a frame as long as the site including it in a frame it is the same as the one serving the page.</p>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-frame-options-strategy" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>strategy</strong> Select the <code>AllowFromStrategy</code> to use when using the ALLOW-FROM policy.</p>
                                        <div class="ulist">
                                            <ul>
                                                <li>
                                                    <p><code>static</code> Use a single static ALLOW-FROM value. The value can be set through the <a href="#nsa-frame-options-value">value</a> attribute.</p>
                                                </li>
                                                <li>
                                                    <p><code>regexp</code> Use a regelur expression to validate incoming requests and if they are allowed. The regular expression can be set through the <a href="#nsa-frame-options-value">value</a> attribute. The request parameter used to retrieve the value to validate can be specified using the <a href="#nsa-frame-options-from-parameter">from-parameter</a>.</p>
                                                </li>
                                                <li>
                                                    <p><code>whitelist</code> A comma-seperated list containing the allowed domains. The comma-seperated list can be set through the <a href="#nsa-frame-options-value">value</a> attribute. The request parameter used to retrieve the value to validate can be specified using the <a href="#nsa-frame-options-from-parameter">from-parameter</a>.</p>
                                                </li>
                                            </ul>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-frame-options-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Instead of using one of the predefined strategies it is also possible to use a custom <code>AllowFromStrategy</code>. The reference to this bean can be specified through this ref attribute.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-frame-options-value" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>value</strong> The value to use when ALLOW-FROM is used a <a href="#nsa-frame-options-strategy">strategy</a>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-frame-options-from-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>from-parameter</strong> Specify the name of the request parameter to use when using regexp or whitelist for the ALLOW-FROM strategy.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-frame-options-parents"><a class="anchor" href="#nsa-frame-options-parents"></a>Parent Elements of &lt;frame-options&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-xss-protection"><a class="anchor" href="#nsa-xss-protection"></a>2.1.8. &lt;xss-protection&gt;</h4>
                        <div class="paragraph">
                            <p>Adds the <a href="http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx">X-XSS-Protection header</a> to the response to assist in protecting against <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent">reflected / Type-1 Cross-Site Scripting (XSS)</a> attacks. This is in no-way a full protection to XSS attacks!</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-xss-protection-attributes"><a class="anchor" href="#nsa-xss-protection-attributes"></a>&lt;xss-protection&gt; Attributes</h5>
                            <div id="nsa-xss-protection-enabled" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>xss-protection-enabled</strong> Enable or Disable <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent">reflected / Type-1 Cross-Site Scripting (XSS)</a> protection.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-xss-protection-block" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>xss-protection-block</strong> When true and xss-protection-enabled is true, adds mode=block to the header. This indicates to the browser that the page should not be loaded at all. When false and xss-protection-enabled is true, the page will still be rendered when an reflected attack is detected but the response will be modified to protect against the attack. Note that there are sometimes ways of bypassing this mode which can often times make blocking the page more desirable.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-xss-protection-parents"><a class="anchor" href="#nsa-xss-protection-parents"></a>Parent Elements of &lt;xss-protection&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-content-type-options"><a class="anchor" href="#nsa-content-type-options"></a>2.1.9. &lt;content-type-options&gt;</h4>
                        <div class="paragraph">
                            <p>Add the X-Content-Type-Options header with the value of nosniff to the response. This <a href="http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx">disables MIME-sniffing</a> for IE8+ and Chrome extensions.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-content-type-options-parents"><a class="anchor" href="#nsa-content-type-options-parents"></a>Parent Elements of &lt;content-type-options&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-header"><a class="anchor" href="#nsa-header"></a>2.1.10. &lt;header&gt;</h4>
                        <div class="paragraph">
                            <p>Add additional headers to the response, both the name and value need to be specified.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-header-attributes"><a class="anchor" href="#nsa-header-attributes"></a>&lt;header-attributes&gt; Attributes</h5>
                            <div id="nsa-header-name" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>header-name</strong> The <code>name</code> of the header.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-header-value" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>value</strong> The <code>value</code> of the header to add.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-header-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Reference to a custom implementation of the <code>HeaderWriter</code> interface.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-header-parents"><a class="anchor" href="#nsa-header-parents"></a>Parent Elements of &lt;header&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-headers">headers</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-anonymous"><a class="anchor" href="#nsa-anonymous"></a>2.1.11. &lt;anonymous&gt;</h4>
                        <div class="paragraph">
                            <p>Adds an <code>AnonymousAuthenticationFilter</code> to the stack and an <code>AnonymousAuthenticationProvider</code>. Required if you are using the <code>IS_AUTHENTICATED_ANONYMOUSLY</code> attribute.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-anonymous-parents"><a class="anchor" href="#nsa-anonymous-parents"></a>Parent Elements of &lt;anonymous&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-anonymous-attributes"><a class="anchor" href="#nsa-anonymous-attributes"></a>&lt;anonymous&gt; Attributes</h5>
                            <div id="nsa-anonymous-enabled" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>enabled</strong> With the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-anonymous-granted-authority" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>granted-authority</strong> The granted authority that should be assigned to the anonymous request. Commonly this is used to assign the anonymous request particular roles, which can subsequently be used in authorization decisions. If unset, defaults to <code>ROLE_ANONYMOUS</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-anonymous-key" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>key</strong> The key shared between the provider and filter. This generally does not need to be set. If unset, it will default to a secure randomly generated value. This means setting this value can improve startup time when using the anonymous functionality since secure random values can take a while to be generated.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-anonymous-username" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>username</strong> The username that should be assigned to the anonymous request. This allows the principal to be identified, which may be important for logging and auditing. if unset, defaults to <code>anonymousUser</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-csrf"><a class="anchor" href="#nsa-csrf"></a>2.1.12. &lt;csrf&gt;</h4>
                        <div class="paragraph">
                            <p>This element will add <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross Site Request Forger (CSRF)</a> protection to the application. It also updates the default RequestCache to only replay "GET" requests upon successful authentication. Additional information can be found in the <a href="#csrf">Cross Site Request Forgery (CSRF)</a> section of the reference.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-csrf-parents"><a class="anchor" href="#nsa-csrf-parents"></a>Parent Elements of &lt;csrf&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-csrf-attributes"><a class="anchor" href="#nsa-csrf-attributes"></a>&lt;csrf&gt; Attributes</h5>
                            <div id="nsa-csrf-token-repository-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>token-repository-ref</strong> The CsrfTokenRepository to use. The default is <code>HttpSessionCsrfTokenRepository</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-csrf-request-matcher-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher-ref</strong> The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS".</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-custom-filter"><a class="anchor" href="#nsa-custom-filter"></a>2.1.13. &lt;custom-filter&gt;</h4>
                        <div class="paragraph">
                            <p>This element is used to add a filter to the filter chain. It doesn`t create any additional beans but is used to select a bean of type <code>javax.servlet.Filter</code> which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. Full details can be found in the <a href="#ns-custom-filters">namespace chapter</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-custom-filter-parents"><a class="anchor" href="#nsa-custom-filter-parents"></a>Parent Elements of &lt;custom-filter&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-custom-filter-attributes"><a class="anchor" href="#nsa-custom-filter-attributes"></a>&lt;custom-filter&gt; Attributes</h5>
                            <div id="nsa-custom-filter-after" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>after</strong> The filter immediately after which the custom-filter should be placed in the chain. This feature will only be needed by advanced users who wish to mix their own filters into the security filter chain and have some knowledge of the standard Spring Security filters. The filter names map to specific Spring Security implementation filters.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-custom-filter-before" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>before</strong> The filter immediately before which the custom-filter should be placed in the chain</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-custom-filter-position" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>position</strong> The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-custom-filter-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>Filter</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-expression-handler"><a class="anchor" href="#nsa-expression-handler"></a>2.1.14. &lt;expression-handler&gt;</h4>
                        <div class="paragraph">
                            <p>Defines the <code>SecurityExpressionHandler</code> instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-expression-handler-parents"><a class="anchor" href="#nsa-expression-handler-parents"></a>Parent Elements of &lt;expression-handler&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-global-method-security">global-method-security</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-expression-handler-attributes"><a class="anchor" href="#nsa-expression-handler-attributes"></a>&lt;expression-handler&gt; Attributes</h5>
                            <div id="nsa-expression-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>SecurityExpressionHandler</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-form-login"><a class="anchor" href="#nsa-form-login"></a>2.1.15. &lt;form-login&gt;</h4>
                        <div class="paragraph">
                            <p>Used to add an <code>UsernamePasswordAuthenticationFilter</code> to the filter stack and an <code>LoginUrlAuthenticationEntryPoint</code> to the application context to provide authentication on demand. This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/spring_security_login" <span class="footnote">[<a id="_footnoteref_25" class="footnote" href="#_footnote_25" title="View footnote.">25</a>]</span> The behaviour can be customized using the <a href="#nsa-form-login-attributes"><code>&lt;form-login&gt;</code> Attributes</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-form-login-parents"><a class="anchor" href="#nsa-form-login-parents"></a>Parent Elements of &lt;form-login&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-form-login-attributes"><a class="anchor" href="#nsa-form-login-attributes"></a>&lt;form-login&gt; Attributes</h5>
                            <div id="nsa-form-login-always-use-default-target" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>always-use-default-target</strong> If set to <code>true</code>, the user will always start at the value given by <a href="#nsa-form-login-default-target-url">default-target-url</a>, regardless of how they arrived at the login page. Maps to the <code>alwaysUseDefaultTargetUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. Default value is <code>false</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-authentication-details-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-details-source-ref</strong> Reference to an <code>AuthenticationDetailsSource</code> which will be used by the authentication filter</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-authentication-failure-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-failure-handler-ref</strong> Can be used as an alternative to <a href="#nsa-form-login-authentication-failure-url">authentication-failure-url</a>, giving you full control over the navigation flow after an authentication failure. The value should be he name of an <code>AuthenticationFailureHandler</code> bean in the application context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-authentication-failure-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-failure-url</strong> Maps to the <code>authenticationFailureUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. Defines the URL the browser will be redirected to on login failure. Defaults to <code>/spring_security_login?login_error</code>, which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-authentication-success-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-success-handler-ref</strong> This can be used as an alternative to <a href="#nsa-form-login-default-target-url">default-target-url</a> and <a href="#nsa-form-login-always-use-default-target">always-use-default-target</a>, giving you full control over the navigation flow after a successful authentication. The value should be the name of an <code>AuthenticationSuccessHandler</code> bean in the application context. By default, an implementation of <code>SavedRequestAwareAuthenticationSuccessHandler</code> is used and injected with the <a href="#nsa-form-login-default-target-url">default-target-url</a>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-default-target-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>default-target-url</strong> Maps to the <code>defaultTargetUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. If not set, the default value is "/" (the application root). A user will be taken to this URL after logging in, provided they were not asked to login while attempting to access a secured resource, when they will be taken to the originally requested URL.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-login-page" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>login-page</strong> The URL that should be used to render the login page. Maps to the <code>loginFormUrl</code> property of the <code>LoginUrlAuthenticationEntryPoint</code>. Defaults to "/spring_security_login".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-login-processing-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>login-processing-url</strong> Maps to the <code>filterProcessesUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. The default value is "/j_spring_security_check".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-password-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>password-parameter</strong> The name of the request parameter which contains the password. Defaults to "j_password".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-form-login-username-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>username-parameter</strong> The name of the request parameter which contains the username. Defaults to "j_username".</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-http-basic"><a class="anchor" href="#nsa-http-basic"></a>2.1.16. &lt;http-basic&gt;</h4>
                        <div class="paragraph">
                            <p>Adds a <code>BasicAuthenticationFilter</code> and <code>BasicAuthenticationEntryPoint</code> to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-http-basic-parents"><a class="anchor" href="#nsa-http-basic-parents"></a>Parent Elements of &lt;http-basic&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-http-basic-attributes"><a class="anchor" href="#nsa-http-basic-attributes"></a>&lt;http-basic&gt; Attributes</h5>
                            <div id="nsa-http-basic-authentication-details-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-details-source-ref</strong> Reference to an <code>AuthenticationDetailsSource</code> which will be used by the authentication filter</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-http-basic-entry-point-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>entry-point-ref</strong> Sets the <code>AuthenticationEntryPoint</code> which is used by the <code>BasicAuthenticationFilter</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-http-firewall"><a class="anchor" href="#nsa-http-firewall"></a>2.1.17. &lt;http-firewall&gt; Element</h4>
                        <div class="paragraph">
                            <p>This is a top-level element which can be used to inject a custom implementation of <code>HttpFirewall</code> into the <code>FilterChainProxy</code> created by the namespace. The default implementation should be suitable for most applications.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-http-firewall-attributes"><a class="anchor" href="#nsa-http-firewall-attributes"></a>&lt;http-firewall&gt; Attributes</h5>
                            <div id="nsa-http-firewall-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>HttpFirewall</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-intercept-url"><a class="anchor" href="#nsa-intercept-url"></a>2.1.18. &lt;intercept-url&gt;</h4>
                        <div class="paragraph">
                            <p>This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. It is used to construct the <code>FilterInvocationSecurityMetadataSource</code> used by the <code>FilterSecurityInterceptor</code>. It is also responsible for configuring a <code>ChannelProcessingFilter</code> if particular URLs need to be accessed by HTTPS, for example. When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. So the most specific matches patterns should come first and the most general should come last.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-intercept-url-parents"><a class="anchor" href="#nsa-intercept-url-parents"></a>Parent Elements of &lt;intercept-url&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-filter-invocation-definition-source">filter-invocation-definition-source</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-filter-security-metadata-source">filter-security-metadata-source</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-intercept-url-attributes"><a class="anchor" href="#nsa-intercept-url-attributes"></a>&lt;intercept-url&gt; Attributes</h5>
                            <div id="nsa-intercept-url-access" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access</strong> Lists the access attributes which will be stored in the <code>FilterInvocationSecurityMetadataSource</code> for the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-intercept-url-filters" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>filters</strong> Can only take the value "none". This will cause any matching request to bypass the Spring Security filter chain entirely. None of the rest of the <code>&lt;http&gt;</code> configuration will have any effect on the request and there will be no security context available for its duration. Access to secured methods during the request will fail.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            This property is invalid for <a href="#nsa-filter-security-metadata-source">filter-security-metadata-source</a>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div id="nsa-intercept-url-method" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>method</strong> The HTTP Method which will be used in combination with the pattern to match an incoming request. If omitted, any method will match. If an identical pattern is specified with and without a method, the method-specific match will take precedence.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-intercept-url-pattern" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>pattern</strong> The pattern which defines the URL path. The content will depend on the <code>request-matcher</code> attribute from the containing http element, so will default to ant path syntax.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-intercept-url-requires-channel" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>requires-channel</strong> Can be "http" or "https" depending on whether a particular URL pattern should be accessed over HTTP or HTTPS respectively. Alternatively the value "any" can be used when there is no preference. If this attribute is present on any <code>&lt;intercept-url&gt;</code> element, then a <code>ChannelProcessingFilter</code> will be added to the filter stack and its additional dependencies added to the application context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="paragraph">
                                <p>If a <code>&lt;port-mappings&gt;</code> configuration is added, this will be used to by the <code>SecureChannelProcessor</code> and <code>InsecureChannelProcessor</code> beans to determine the ports used for redirecting to HTTP/HTTPS.</p>
                            </div>
                            <div class="admonitionblock note">
                                <table>
                                    <tr>
                                        <td class="icon">
                                            <i class="icon-note" title="Note"></i>
                                        </td>
                                        <td class="content">
                                            This property is invalid for <a href="#nsa-filter-security-metadata-source">filter-security-metadata-source</a>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-jee"><a class="anchor" href="#nsa-jee"></a>2.1.19. &lt;jee&gt;</h4>
                        <div class="paragraph">
                            <p>Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-jee-parents"><a class="anchor" href="#nsa-jee-parents"></a>Parent Elements of &lt;jee&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-jee-attributes"><a class="anchor" href="#nsa-jee-attributes"></a>&lt;jee&gt; Attributes</h5>
                            <div id="nsa-jee-mappable-roles" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>mappable-roles</strong> A comma-separate list of roles to look for in the incoming HttpServletRequest.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jee-user-service-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-service-ref</strong> A reference to a user-service (or UserDetailsService bean) Id</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-logout"><a class="anchor" href="#nsa-logout"></a>2.1.20. &lt;logout&gt;</h4>
                        <div class="paragraph">
                            <p>Adds a <code>LogoutFilter</code> to the filter stack. This is configured with a <code>SecurityContextLogoutHandler</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-logout-parents"><a class="anchor" href="#nsa-logout-parents"></a>Parent Elements of &lt;logout&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-logout-attributes"><a class="anchor" href="#nsa-logout-attributes"></a>&lt;logout&gt; Attributes</h5>
                            <div id="nsa-logout-delete-cookies" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>delete-cookies</strong> A comma-separated list of the names of cookies which should be deleted when the user logs out.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-logout-invalidate-session" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>invalidate-session</strong> Maps to the <code>invalidateHttpSession</code> of the <code>SecurityContextLogoutHandler</code>. Defaults to "true", so the session will be invalidated on logout.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-logout-logout-success-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>logout-success-url</strong> The destination URL which the user will be taken to after logging out. Defaults to "/".</p>
                                        <div class="paragraph">
                                            <p>Setting this attribute will inject the <code>SessionManagementFilter</code> with a <code>SimpleRedirectInvalidSessionStrategy</code> configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.</p>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-logout-logout-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>logout-url</strong> The URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/j_spring_security_logout".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-logout-success-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>success-handler-ref</strong> May be used to supply an instance of <code>LogoutSuccessHandler</code> which will be invoked to control the navigation after logging out.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-openid-login"><a class="anchor" href="#nsa-openid-login"></a>2.1.21. &lt;openid-login&gt;</h4>
                        <div class="paragraph">
                            <p>Similar to <code>&lt;form-login&gt;</code> and has the same attributes. The default value for <code>login-processing-url</code> is "/j_spring_openid_security_check". An <code>OpenIDAuthenticationFilter</code> and <code>OpenIDAuthenticationProvider</code> will be registered. The latter requires a reference to a <code>UserDetailsService</code>. Again, this can be specified by <code>id</code>, using the <code>user-service-ref</code> attribute, or will be located automatically in the application context.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-openid-login-parents"><a class="anchor" href="#nsa-openid-login-parents"></a>Parent Elements of &lt;openid-login&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-openid-login-attributes"><a class="anchor" href="#nsa-openid-login-attributes"></a>&lt;openid-login&gt; Attributes</h5>
                            <div id="nsa-openid-login-always-use-default-target" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>always-use-default-target</strong> Whether the user should always be redirected to the default-target-url after login.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-authentication-details-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-details-source-ref</strong> Reference to an AuthenticationDetailsSource which will be used by the authentication filter</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-authentication-failure-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-failure-handler-ref</strong> Reference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-authentication-failure-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-failure-url</strong> The URL for the login failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /spring_security_login?login_error and a corresponding filter to render that login failure URL when requested.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-authentication-success-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-success-handler-ref</strong> Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with <a href="#nsa-openid-login-default-target-url">default-target-url</a> (or <a href="#nsa-openid-login-always-use-default-target">always-use-default-target</a>) as the implementation should always deal with navigation to the subsequent destination</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-default-target-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>default-target-url</strong> The URL that will be redirected to after successful authentication, if the user`s previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, defaults to the root of the application.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-login-page" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>login-page</strong> The URL for the login page. If no login URL is specified, Spring Security will automatically create a login URL at /spring_security_login and a corresponding filter to render that login URL when requested.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-login-processing-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>login-processing-url</strong> The URL that the login form is posted to. If unspecified, it defaults to /j_spring_security_check.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-password-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>password-parameter</strong> The name of the request parameter which contains the password. Defaults to "j_password".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-user-service-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-service-ref</strong> A reference to a user-service (or UserDetailsService bean) Id</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-login-username-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>username-parameter</strong> The name of the request parameter which contains the username. Defaults to "j_username".</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-openid-login-children"><a class="anchor" href="#nsa-openid-login-children"></a>Child Elements of &lt;openid-login&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-attribute-exchange">attribute-exchange</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-attribute-exchange"><a class="anchor" href="#nsa-attribute-exchange"></a>2.1.22. &lt;attribute-exchange&gt;</h4>
                        <div class="paragraph">
                            <p>The <code>attribute-exchange</code> element defines the list of attributes which should be requested from the identity provider. An example can be found in the <a href="#ns-openid">OpenID Support</a> section of the namespace configuration chapter. More than one can be used, in which case each must have an <code>identifier-match</code> attribute, containing a regular expression which is matched against the supplied OpenID identifier. This allows different attribute lists to be fetched from different providers (Google, Yahoo etc).</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-attribute-exchange-parents"><a class="anchor" href="#nsa-attribute-exchange-parents"></a>Parent Elements of &lt;attribute-exchange&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-openid-login">openid-login</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-attribute-exchange-attributes"><a class="anchor" href="#nsa-attribute-exchange-attributes"></a>&lt;attribute-exchange&gt; Attributes</h5>
                            <div id="nsa-attribute-exchange-identifier-match" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>identifier-match</strong> A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-attribute-exchange-children"><a class="anchor" href="#nsa-attribute-exchange-children"></a>Child Elements of &lt;attribute-exchange&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-openid-attribute">openid-attribute</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-openid-attribute"><a class="anchor" href="#nsa-openid-attribute"></a>2.1.23. &lt;openid-attribute&gt;</h4>
                        <div class="paragraph">
                            <p>Attributes used when making an OpenID AX <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request"> Fetch Request</a></p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-openid-attribute-parents"><a class="anchor" href="#nsa-openid-attribute-parents"></a>Parent Elements of &lt;openid-attribute&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-attribute-exchange">attribute-exchange</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-openid-attribute-attributes"><a class="anchor" href="#nsa-openid-attribute-attributes"></a>&lt;openid-attribute&gt; Attributes</h5>
                            <div id="nsa-openid-attribute-count" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>count</strong> Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-attribute-name" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>name</strong> Specifies the name of the attribute that you wish to get back. For example, email.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-attribute-required" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>required</strong> Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-openid-attribute-type" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>type</strong> Specifies the attribute type. For example, <a href="http://axschema.org/contact/email">http://axschema.org/contact/email</a>. See your OP`s documentation for valid attribute types.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-port-mappings"><a class="anchor" href="#nsa-port-mappings"></a>2.1.24. &lt;port-mappings&gt;</h4>
                        <div class="paragraph">
                            <p>By default, an instance of <code>PortMapperImpl</code> will be added to the configuration for use in redirecting to secure and insecure URLs. This element can optionally be used to override the default mappings which that class defines. Each child <code>&lt;port-mapping&gt;</code> element defines a pair of HTTP:HTTPS ports. The default mappings are 80:443 and 8080:8443. An example of overriding these can be found in the <a href="#ns-requires-channel">namespace introduction</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-port-mappings-parents"><a class="anchor" href="#nsa-port-mappings-parents"></a>Parent Elements of &lt;port-mappings&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-port-mappings-children"><a class="anchor" href="#nsa-port-mappings-children"></a>Child Elements of &lt;port-mappings&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-port-mapping">port-mapping</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-port-mapping"><a class="anchor" href="#nsa-port-mapping"></a>2.1.25. &lt;port-mapping&gt;</h4>
                        <div class="paragraph">
                            <p>Provides a method to map http ports to https ports when forcing a redirect.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-port-mapping-parents"><a class="anchor" href="#nsa-port-mapping-parents"></a>Parent Elements of &lt;port-mapping&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-port-mappings">port-mappings</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-port-mapping-attributes"><a class="anchor" href="#nsa-port-mapping-attributes"></a>&lt;port-mapping&gt; Attributes</h5>
                            <div id="nsa-port-mapping-http" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>http</strong> The http port to use.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-port-mapping-https" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>https</strong> The https port to use.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-remember-me"><a class="anchor" href="#nsa-remember-me"></a>2.1.26. &lt;remember-me&gt;</h4>
                        <div class="paragraph">
                            <p>Adds the <code>RememberMeAuthenticationFilter</code> to the stack. This in turn will be configured with either a <code>TokenBasedRememberMeServices</code>, a <code>PersistentTokenBasedRememberMeServices</code> or a user-specified bean implementing <code>RememberMeServices</code> depending on the attribute settings.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-remember-me-parents"><a class="anchor" href="#nsa-remember-me-parents"></a>Parent Elements of &lt;remember-me&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-remember-me-attributes"><a class="anchor" href="#nsa-remember-me-attributes"></a>&lt;remember-me&gt; Attributes</h5>
                            <div id="nsa-remember-me-authentication-success-handler-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-success-handler-ref</strong> Sets the <code>authenticationSuccessHandler</code> property on the <code>RememberMeAuthenticationFilter</code> if custom navigation is required. The value should be the name of a <code>AuthenticationSuccessHandler</code> bean in the application context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-data-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>data-source-ref</strong> A reference to a <code>DataSource</code> bean. If this is set, <code>PersistentTokenBasedRememberMeServices</code> will be used and configured with a <code>JdbcTokenRepositoryImpl</code> instance.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-remember-me-parameter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>remember-me-parameter</strong> The name of the request parameter which toggles remember-me authentication. Defaults to "_spring_security_remember_me". Maps to the "parameter" property of <code>AbstractRememberMeServices</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-key" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>key</strong> Maps to the "key" property of <code>AbstractRememberMeServices</code>. Should be set to a unique value to ensure that remember-me cookies are only valid within the one application <span class="footnote">[<a id="_footnoteref_26" class="footnote" href="#_footnote_26" title="View footnote.">26</a>]</span>. If this is not set a secure random value will be generated. Since generating secure random values can take a while, setting this value explicitly can help improve startup times when using the remember me functionality.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-services-alias" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>services-alias</strong> Exports the internally defined <code>RememberMeServices</code> as a bean alias, allowing it to be used by other beans in the application context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-services-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>services-ref</strong> Allows complete control of the <code>RememberMeServices</code> implementation that will be used by the filter. The value should be the <code>id</code> of a bean in the application context which implements this interface. Should also implement <code>LogoutHandler</code> if a logout filter is in use.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-token-repository-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>token-repository-ref</strong> Configures a <code>PersistentTokenBasedRememberMeServices</code> but allows the use of a custom <code>PersistentTokenRepository</code> bean.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-token-validity-seconds" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>token-validity-seconds</strong> Maps to the <code>tokenValiditySeconds</code> property of <code>AbstractRememberMeServices</code>. Specifies the period in seconds for which the remember-me cookie should be valid. By default it will be valid for 14 days.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-use-secure-cookie" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>use-secure-cookie</strong> It is recommended that remember-me cookies are only submitted over HTTPS and thus should be flagged as "secure". By default, a secure cookie will be used if the connection over which the login request is made is secure (as it should be). If you set this property to <code>false</code>, secure cookies will not be used. Setting it to <code>true</code> will always set the secure flag on the cookie. This attribute maps to the <code>useSecureCookie</code> property of <code>AbstractRememberMeServices</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-remember-me-user-service-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-service-ref</strong> The remember-me services implementations require access to a <code>UserDetailsService</code>, so there has to be one defined in the application context. If there is only one, it will be selected and used automatically by the namespace configuration. If there are multiple instances, you can specify a bean <code>id</code> explicitly using this attribute.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-request-cache"><a class="anchor" href="#nsa-request-cache"></a>2.1.27. &lt;request-cache&gt; Element</h4>
                        <div class="paragraph">
                            <p>Sets the <code>RequestCache</code> instance which will be used by the <code>ExceptionTranslationFilter</code> to store request information before invoking an <code>AuthenticationEntryPoint</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-request-cache-parents"><a class="anchor" href="#nsa-request-cache-parents"></a>Parent Elements of &lt;request-cache&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-request-cache-attributes"><a class="anchor" href="#nsa-request-cache-attributes"></a>&lt;request-cache&gt; Attributes</h5>
                            <div id="nsa-request-cache-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that is a <code>RequestCache</code>.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-session-management"><a class="anchor" href="#nsa-session-management"></a>2.1.28. &lt;session-management&gt;</h4>
                        <div class="paragraph">
                            <p>Session-management related functionality is implemented by the addition of a <code>SessionManagementFilter</code> to the filter stack.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-session-management-parents"><a class="anchor" href="#nsa-session-management-parents"></a>Parent Elements of &lt;session-management&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-session-management-attributes"><a class="anchor" href="#nsa-session-management-attributes"></a>&lt;session-management&gt; Attributes</h5>
                            <div id="nsa-session-management-invalid-session-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>invalid-session-url</strong> Setting this attribute will inject the <code>SessionManagementFilter</code> with a <code>SimpleRedirectInvalidSessionStrategy</code> configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-session-management-session-authentication-error-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>session-authentication-error-url</strong> Defines the URL of the error page which should be shown when the SessionAuthenticationStrategy raises an exception. If not set, an unauthorized (401) error code will be returned to the client. Note that this attribute doesn`t apply if the error occurs during a form-based login, where the URL for authentication failure will take precedence.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-session-management-session-authentication-strategy-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>session-authentication-strategy-ref</strong> Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-session-management-session-fixation-protection" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>session-fixation-protection</strong> Indicates how session fixation protection will be applied when a user authenticates. If set to "none", no protection will be applied. "newSession" will create a new empty session, with only Spring Security-related attributes migrated. "migrateSession" will create a new session and copy all session attributes to the new session. In Servlet 3.1 (Java EE 7) and newer containers, specifying "changeSessionId" will keep the existing session and use the container-supplied session fixation protection (HttpServletRequest#changeSessionId()). Defaults to "changeSessionId" in Servlet 3.1 and newer containers, "migrateSession" in older containers. Throws an exception if "changeSessionId" is used in older containers.</p>
                                        <div class="paragraph">
                                            <p>If session fixation protection is enabled, the <code>SessionManagementFilter</code> is injected with an appropriately configured <code>DefaultSessionAuthenticationStrategy</code>. See the Javadoc for this class for more details.</p>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-session-management-children"><a class="anchor" href="#nsa-session-management-children"></a>Child Elements of &lt;session-management&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-concurrency-control">concurrency-control</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-concurrency-control"><a class="anchor" href="#nsa-concurrency-control"></a>2.1.29. &lt;concurrency-control&gt;</h4>
                        <div class="paragraph">
                            <p>Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. A <code>ConcurrentSessionFilter</code> will be created, and a <code>ConcurrentSessionControlAuthenticationStrategy</code> will be used with the <code>SessionManagementFilter</code>. If a <code>form-login</code> element has been declared, the strategy object will also be injected into the created authentication filter. An instance of <code>SessionRegistry</code> (a <code>SessionRegistryImpl</code> instance unless the user wishes to use a custom bean) will be created for use by the strategy.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-concurrency-control-parents"><a class="anchor" href="#nsa-concurrency-control-parents"></a>Parent Elements of &lt;concurrency-control&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-session-management">session-management</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-concurrency-control-attributes"><a class="anchor" href="#nsa-concurrency-control-attributes"></a>&lt;concurrency-control&gt; Attributes</h5>
                            <div id="nsa-concurrency-control-error-if-maximum-exceeded" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>error-if-maximum-exceeded</strong> If set to "true" a <code>SessionAuthenticationException</code> will be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-concurrency-control-expired-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>expired-url</strong> The URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. Should be set unless <code>exception-if-maximum-exceeded</code> is set. If no value is supplied, an expiry message will just be written directly back to the response.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-concurrency-control-max-sessions" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>max-sessions</strong> Maps to the <code>maximumSessions</code> property of <code>ConcurrentSessionControlAuthenticationStrategy</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-concurrency-control-session-registry-alias" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>session-registry-alias</strong> It can also be useful to have a reference to the internal session registry for use in your own beans or an admin interface. You can expose the internal bean using the <code>session-registry-alias</code> attribute, giving it a name that you can use elsewhere in your configuration.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-concurrency-control-session-registry-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>session-registry-ref</strong> The user can supply their own <code>SessionRegistry</code> implementation using the <code>session-registry-ref</code> attribute. The other concurrent session control beans will be wired up to use it.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-x509"><a class="anchor" href="#nsa-x509"></a>2.1.30. &lt;x509&gt;</h4>
                        <div class="paragraph">
                            <p>Adds support for X.509 authentication. An <code>X509AuthenticationFilter</code> will be added to the stack and an <code>Http403ForbiddenEntryPoint</code> bean will be created. The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code). A <code>PreAuthenticatedAuthenticationProvider</code> will also be created which delegates the loading of user authorities to a <code>UserDetailsService</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-x509-parents"><a class="anchor" href="#nsa-x509-parents"></a>Parent Elements of &lt;x509&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-http">http</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-x509-attributes"><a class="anchor" href="#nsa-x509-attributes"></a>&lt;x509&gt; Attributes</h5>
                            <div id="nsa-x509-authentication-details-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-details-source-ref</strong> A reference to an <code>AuthenticationDetailsSource</code></p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-x509-subject-principal-regex" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>subject-principal-regex</strong> Defines a regular expression which will be used to extract the username from the certificate (for use with the <code>UserDetailsService</code>).</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-x509-user-service-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-service-ref</strong> Allows a specific <code>UserDetailsService</code> to be used with X.509 in the case where multiple instances are configured. If not set, an attempt will be made to locate a suitable instance automatically and use that.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-filter-chain-map"><a class="anchor" href="#nsa-filter-chain-map"></a>2.1.31. &lt;filter-chain-map&gt;</h4>
                        <div class="paragraph">
                            <p>Used to explicitly configure a FilterChainProxy instance with a FilterChainMap</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-chain-map-attributes"><a class="anchor" href="#nsa-filter-chain-map-attributes"></a>&lt;filter-chain-map&gt; Attributes</h5>
                            <div id="nsa-filter-chain-map-path-type" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>path-type</strong> Superseded by the <a href="#nsa-filter-chain-map-request-matcher">request-matcher</a> attribute</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-chain-map-request-matcher" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-chain-map-children"><a class="anchor" href="#nsa-filter-chain-map-children"></a>Child Elements of &lt;filter-chain-map&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-filter-chain">filter-chain</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-filter-chain"><a class="anchor" href="#nsa-filter-chain"></a>2.1.32. &lt;filter-chain&gt;</h4>
                        <div class="paragraph">
                            <p>Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-chain-parents"><a class="anchor" href="#nsa-filter-chain-parents"></a>Parent Elements of &lt;filter-chain&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-filter-chain-map">filter-chain-map</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-chain-attributes"><a class="anchor" href="#nsa-filter-chain-attributes"></a>&lt;filter-chain&gt; Attributes</h5>
                            <div id="nsa-filter-chain-filters" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>filters</strong> A comma separated list of references to Spring beans that implement <code>Filter</code>. The value "none" means that no <code>Filter</code>'s should be used for this <code>FilterChain</code>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-chain-pattern" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>pattern</strong> A-pattern that creates RequestMatcher in combination with the <a href="#nsa-filter-chain-map-request-matcher">request-matcher</a></p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-chain-request-matcher-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher-ref</strong> A reference to a <code>RequestMatcher</code> that will be used to determine if the <code>Filter</code>'s from the <code>filters</code> attribute should be invoked.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-filter-invocation-definition-source"><a class="anchor" href="#nsa-filter-invocation-definition-source"></a>2.1.33. &lt;filter-invocation-definition-source&gt;</h4>
                        <div class="paragraph">
                            <p>Deprecated synonym for filter-security-metadata-source</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-invocation-definition-source-attributes"><a class="anchor" href="#nsa-filter-invocation-definition-source-attributes"></a>&lt;filter-invocation-definition-source&gt; Attributes</h5>
                            <div id="nsa-filter-invocation-definition-source-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-invocation-definition-source-lowercase-comparisons" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>lowercase-comparisons</strong> Compare after forcing to lowercase</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-invocation-definition-source-path-type" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>path-type</strong> Superseded by <a href="#nsa-filter-invocation-definition-source-request-matcher">request-matcher</a></p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-invocation-definition-source-request-matcher" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-invocation-definition-source-use-expressions" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in &lt;intercept-url&gt; elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-invocation-definition-source-children"><a class="anchor" href="#nsa-filter-invocation-definition-source-children"></a>Child Elements of &lt;filter-invocation-definition-source&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-intercept-url">intercept-url</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-filter-security-metadata-source"><a class="anchor" href="#nsa-filter-security-metadata-source"></a>2.1.34. &lt;filter-security-metadata-source&gt;</h4>
                        <div class="paragraph">
                            <p>Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the&lt;http&gt; element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-security-metadata-source-attributes"><a class="anchor" href="#nsa-filter-security-metadata-source-attributes"></a>&lt;filter-security-metadata-source&gt; Attributes</h5>
                            <div id="nsa-filter-security-metadata-source-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-security-metadata-source-lowercase-comparisons" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>lowercase-comparisons</strong> Compare after forcing to lower case</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-security-metadata-source-path-type" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>path-type</strong> Superseded by <a href="#nsa-filter-security-metadata-source-request-matcher">request-matcher</a></p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-security-metadata-source-request-matcher" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-filter-security-metadata-source-use-expressions" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in &lt;intercept-url&gt; elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-filter-security-metadata-source-children"><a class="anchor" href="#nsa-filter-security-metadata-source-children"></a>Child Elements of &lt;filter-security-metadata-source&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-intercept-url">intercept-url</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="nsa-authentication"><a class="anchor" href="#nsa-authentication"></a>2.2. Authentication Services</h3>
                    <div class="paragraph">
                        <p>Before Spring Security 3.0, an <code>AuthenticationManager</code> was automatically registered internally. Now you must register one explicitly using the <code>&lt;authentication-manager&gt;</code> element. This creates an instance of Spring Security`s <code>ProviderManager</code> class, which needs to be configured with a list of one or more <code>AuthenticationProvider</code> instances. These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the <code>authentication-provider</code> element.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-authentication-manager"><a class="anchor" href="#nsa-authentication-manager"></a>2.2.1. &lt;authentication-manager&gt;</h4>
                        <div class="paragraph">
                            <p>Every Spring Security application which uses the namespace must have include this element somewhere. It is responsible for registering the <code>AuthenticationManager</code> which provides authentication services to the application. All elements which create <code>AuthenticationProvider</code> instances should be children of this element.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-authentication-manager-attributes"><a class="anchor" href="#nsa-authentication-manager-attributes"></a>&lt;authentication-manager&gt; Attributes</h5>
                            <div id="nsa-authentication-manager-alias" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>alias</strong> This attribute allows you to define an alias name for the internal instance for use in your own configuration. Its use is described in the<a href="#ns-auth-manager">namespace introduction</a>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-authentication-manager-erase-credentials" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>erase-credentials</strong> If set to true, the AuthenticationManger will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. Literally it maps to the <code>eraseCredentialsAfterAuthentication</code> property of the <code>ProviderManager</code>. This is discussed in the <a href="#core-services-erasing-credentials">Core Services</a> chapter.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-authentication-manager-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> This attribute allows you to define an id for the internal instance for use in your own configuration. It is the same a the alias element, but provides a more consistent experience with elements that use the id attribute.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-authentication-manager-children"><a class="anchor" href="#nsa-authentication-manager-children"></a>Child Elements of &lt;authentication-manager&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-authentication-provider">authentication-provider</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-ldap-authentication-provider">ldap-authentication-provider</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-authentication-provider"><a class="anchor" href="#nsa-authentication-provider"></a>2.2.2. &lt;authentication-provider&gt;</h4>
                        <div class="paragraph">
                            <p>Unless used with a <code>ref</code> attribute, this element is shorthand for configuring a <a href="#core-services-dao-provider">DaoAuthenticationProvider</a>. <code>DaoAuthenticationProvider</code> loads user information from a <code>UserDetailsService</code> and compares the username/password combination with the values supplied at login. The <code>UserDetailsService</code> instance can be defined either by using an available namespace element ( <code>jdbc-user-service</code> or by using the <code>user-service-ref</code> attribute to point to a bean defined elsewhere in the application context). You can find examples of these variations in the <a href="#ns-auth-providers">namespace introduction</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-authentication-provider-parents"><a class="anchor" href="#nsa-authentication-provider-parents"></a>Parent Elements of &lt;authentication-provider&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-authentication-manager">authentication-manager</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-authentication-provider-attributes"><a class="anchor" href="#nsa-authentication-provider-attributes"></a>&lt;authentication-provider&gt; Attributes</h5>
                            <div id="nsa-authentication-provider-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements `AuthenticationProvider `.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="paragraph">
                                <p>If you have written your own <code>AuthenticationProvider</code> implementation (or want to configure one of Spring Security`s own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal <code>ProviderManager</code>'s list:</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint xml language-xml"><code>
&lt;security:authentication-manager&gt;
  &lt;security:authentication-provider ref="myAuthenticationProvider" /&gt;
&lt;/security:authentication-manager&gt;
&lt;bean id="myAuthenticationProvider" class="com.something.MyAuthenticationProvider"/&gt;
</code></pre>
                                </div>
                            </div>
                            <div id="nsa-authentication-provider-user-service-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-service-ref</strong> A reference to a bean that implements UserDetailsService that may be created using the standard bean element or the custom user-service element.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-authentication-provider-children"><a class="anchor" href="#nsa-authentication-provider-children"></a>Child Elements of &lt;authentication-provider&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-jdbc-user-service">jdbc-user-service</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-ldap-user-service">ldap-user-service</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-password-encoder">password-encoder</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-user-service">user-service</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-jdbc-user-service"><a class="anchor" href="#nsa-jdbc-user-service"></a>2.2.3. &lt;jdbc-user-service&gt;</h4>
                        <div class="paragraph">
                            <p>Causes creation of a JDBC-based UserDetailsService.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-jdbc-user-service-attributes"><a class="anchor" href="#nsa-jdbc-user-service-attributes"></a>&lt;jdbc-user-service&gt; Attributes</h5>
                            <div id="nsa-jdbc-user-service-authorities-by-username-query" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authorities-by-username-query</strong> An SQL statement to query for a user`s granted authorities given a username.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="paragraph">
                                <p>The default is</p>
                            </div>
                            <div class="listingblock">
                                <div class="content">
                                    <pre class="prettyprint"><code>select username, authority from authorities where username = ?</code></pre>
                                </div>
                            </div>
                            <div id="nsa-jdbc-user-service-cache-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>cache-ref</strong> Defines a reference to a cache for use with a UserDetailsService.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jdbc-user-service-data-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>data-source-ref</strong> The bean ID of the DataSource which provides the required tables.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jdbc-user-service-group-authorities-by-username-query" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-authorities-by-username-query</strong> An SQL statement to query user`s group authorities given a username. The default is</p>
                                        <div class="listingblock">
                                            <div class="content">
                                                <pre class="prettyprint"><code>select
  g.id, g.group_name, ga.authority
from
  groups g, group_members gm, group_authorities ga
where
  gm.username = ? and g.id = ga.group_id and g.id = gm.group_id</code></pre>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jdbc-user-service-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jdbc-user-service-role-prefix" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-jdbc-user-service-users-by-username-query" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>users-by-username-query</strong> An SQL statement to query a username, password, and enabled status given a username. The default is</p>
                                        <div class="listingblock">
                                            <div class="content">
                                                <pre class="prettyprint"><code>select username, password, enabled from users where username = ?</code></pre>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-password-encoder"><a class="anchor" href="#nsa-password-encoder"></a>2.2.4. &lt;password-encoder&gt;</h4>
                        <div class="paragraph">
                            <p>Authentication providers can optionally be configured to use a password encoder as described in the <a href="#ns-password-encoder">namespace introduction</a>. This will result in the bean being injected with the appropriate <code>PasswordEncoder</code> instance, potentially with an accompanying <code>SaltSource</code> bean to provide salt values for hashing.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-encoder-parents"><a class="anchor" href="#nsa-password-encoder-parents"></a>Parent Elements of &lt;password-encoder&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-authentication-provider">authentication-provider</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-password-compare">password-compare</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-encoder-attributes"><a class="anchor" href="#nsa-password-encoder-attributes"></a>&lt;password-encoder&gt; Attributes</h5>
                            <div id="nsa-password-encoder-base64" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>base64</strong> Whether a string should be base64 encoded</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-password-encoder-hash" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>hash</strong> Defines the hashing algorithm used on user passwords. We recommend strongly against using MD4, as it is a very weak hashing algorithm.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-password-encoder-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements `PasswordEncoder `.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-encoder-children"><a class="anchor" href="#nsa-password-encoder-children"></a>Child Elements of &lt;password-encoder&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-salt-source">salt-source</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-salt-source"><a class="anchor" href="#nsa-salt-source"></a>2.2.5. &lt;salt-source&gt;</h4>
                        <div class="paragraph">
                            <p>Password salting strategy. A system-wide constant or a property from the UserDetails object can be used.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-salt-source-parents"><a class="anchor" href="#nsa-salt-source-parents"></a>Parent Elements of &lt;salt-source&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-password-encoder">password-encoder</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-salt-source-attributes"><a class="anchor" href="#nsa-salt-source-attributes"></a>&lt;salt-source&gt; Attributes</h5>
                            <div id="nsa-salt-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-salt-source-system-wide" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>system-wide</strong> A single value that will be used as the salt for a password encoder.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-salt-source-user-property" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-property</strong> A property of the UserDetails object which will be used as salt by a password encoder. Typically something like "username" might be used.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-user-service"><a class="anchor" href="#nsa-user-service"></a>2.2.6. &lt;user-service&gt;</h4>
                        <div class="paragraph">
                            <p>Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-user-service-attributes"><a class="anchor" href="#nsa-user-service-attributes"></a>&lt;user-service&gt; Attributes</h5>
                            <div id="nsa-user-service-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-user-service-properties" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>properties</strong> The location of a Properties file where each line is in the format of</p>
                                        <div class="listingblock">
                                            <div class="content">
                                                <pre class="prettyprint"><code>username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]</code></pre>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-user-service-children"><a class="anchor" href="#nsa-user-service-children"></a>Child Elements of &lt;user-service&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-user">user</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-user"><a class="anchor" href="#nsa-user"></a>2.2.7. &lt;user&gt;</h4>
                        <div class="paragraph">
                            <p>Represents a user in the application.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-user-parents"><a class="anchor" href="#nsa-user-parents"></a>Parent Elements of &lt;user&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-user-service">user-service</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-user-attributes"><a class="anchor" href="#nsa-user-attributes"></a>&lt;user&gt; Attributes</h5>
                            <div id="nsa-user-authorities" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authorities</strong> One of more authorities granted to the user. Separate authorities with a comma (but no space). For example, "ROLE_USER,ROLE_ADMINISTRATOR"</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-user-disabled" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>disabled</strong> Can be set to "true" to mark an account as disabled and unusable.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-user-locked" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>locked</strong> Can be set to "true" to mark an account as locked and unusable.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-user-name" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>name</strong> The username assigned to the user.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-user-password" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>password</strong> The password assigned to the user. This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. If omitted, the namespace will generate a random value, preventing its accidental use for authentication. Cannot be empty.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="nsa-method-security"><a class="anchor" href="#nsa-method-security"></a>2.3. Method Security</h3>
                    <div class="sect3">
                        <h4 id="nsa-global-method-security"><a class="anchor" href="#nsa-global-method-security"></a>2.3.1. &lt;global-method-security&gt;</h4>
                        <div class="paragraph">
                            <p>This element is the primary means of adding support for securing methods on Spring Security beans. Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-global-method-security-attributes"><a class="anchor" href="#nsa-global-method-security-attributes"></a>&lt;global-method-security&gt; Attributes</h5>
                            <div id="nsa-global-method-security-access-decision-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access-decision-manager-ref</strong> Method security uses the same <code>AccessDecisionManager</code> configuration as web security, but this can be overridden using this attribute. By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-authentication-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>authentication-manager-ref</strong> A reference to an <code>AuthenticationManager</code> that should be used for method security.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-jsr250-annotations" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>jsr250-annotations</strong> Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Setting this to true also adds a <code>Jsr250Voter</code> to the <code>AccessDecisionManager</code>, so you need to make sure you do this if you are using a custom implementation and want to use these annotations.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-metadata-source-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>metadata-source-ref</strong> An external <code>MethodSecurityMetadataSource</code> instance can be supplied which will take priority over other sources (such as the default annotations).</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-mode" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>mode</strong> This attribute can be set to "aspectj" to specify that AspectJ should be used instead of the default Spring AOP. Secured methods must be woven with the <code>AnnotationSecurityAspect</code> from the <code>spring-security-aspects</code> module.</p>
                                    </li>
                                </ul>
                            </div>
                            <div class="paragraph">
                                <p>It is important to note that AspectJ follows Java`s rule that annotations on interfaces are not inherited. This means that methods that define the Security annotaitons on the interface will not be secured. Instead, you must place the Security annotation on the class when using AspectJ.</p>
                            </div>
                            <div id="nsa-global-method-security-order" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>order</strong> Allows the advice "order" to be set for the method security interceptor.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-pre-post-annotations" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>pre-post-annotations</strong> Specifies whether the use of Spring Security`s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. Defaults to "disabled".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-proxy-target-class" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>proxy-target-class</strong> If true, class based proxying will be used instead of interface based proxying.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-run-as-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>run-as-manager-ref</strong> A reference to an optional <code>RunAsManager</code> implementation which will be used by the configured <code>MethodSecurityInterceptor</code></p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-global-method-security-secured-annotations" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>secured-annotations</strong> Specifies whether the use of Spring Security`s @Secured annotations should be enabled for this application context. Defaults to "disabled".</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-global-method-security-children"><a class="anchor" href="#nsa-global-method-security-children"></a>Child Elements of &lt;global-method-security&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-after-invocation-provider">after-invocation-provider</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-expression-handler">expression-handler</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-protect-pointcut">protect-pointcut</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-after-invocation-provider"><a class="anchor" href="#nsa-after-invocation-provider"></a>2.3.2. &lt;after-invocation-provider&gt;</h4>
                        <div class="paragraph">
                            <p>This element can be used to decorate an <code>AfterInvocationProvider</code> for use by the security interceptor maintained by the <code>&lt;global-method-security&gt;</code> namespace. You can define zero or more of these within the <code>global-method-security</code> element, each with a <code>ref</code> attribute pointing to an <code>AfterInvocationProvider</code> bean instance within your application context.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-after-invocation-provider-parents"><a class="anchor" href="#nsa-after-invocation-provider-parents"></a>Parent Elements of &lt;after-invocation-provider&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-global-method-security">global-method-security</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-after-invocation-provider-attributes"><a class="anchor" href="#nsa-after-invocation-provider-attributes"></a>&lt;after-invocation-provider&gt; Attributes</h5>
                            <div id="nsa-after-invocation-provider-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean that implements ` AfterInvocationProvider`.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-pre-post-annotation-handling"><a class="anchor" href="#nsa-pre-post-annotation-handling"></a>2.3.3. &lt;pre-post-annotation-handling&gt;</h4>
                        <div class="paragraph">
                            <p>Allows the default expression-based mechanism for handling Spring Security`s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-pre-post-annotation-handling-parents"><a class="anchor" href="#nsa-pre-post-annotation-handling-parents"></a>Parent Elements of &lt;pre-post-annotation-handling&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-global-method-security">global-method-security</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-pre-post-annotation-handling-children"><a class="anchor" href="#nsa-pre-post-annotation-handling-children"></a>Child Elements of &lt;pre-post-annotation-handling&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-invocation-attribute-factory">invocation-attribute-factory</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-post-invocation-advice">post-invocation-advice</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-pre-invocation-advice">pre-invocation-advice</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-invocation-attribute-factory"><a class="anchor" href="#nsa-invocation-attribute-factory"></a>2.3.4. &lt;invocation-attribute-factory&gt;</h4>
                        <div class="paragraph">
                            <p>Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-invocation-attribute-factory-parents"><a class="anchor" href="#nsa-invocation-attribute-factory-parents"></a>Parent Elements of &lt;invocation-attribute-factory&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-invocation-attribute-factory-attributes"><a class="anchor" href="#nsa-invocation-attribute-factory-attributes"></a>&lt;invocation-attribute-factory&gt; Attributes</h5>
                            <div id="nsa-invocation-attribute-factory-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-post-invocation-advice"><a class="anchor" href="#nsa-post-invocation-advice"></a>2.3.5. &lt;post-invocation-advice&gt;</h4>
                        <div class="paragraph">
                            <p>Customizes the <code>PostInvocationAdviceProvider</code> with the ref as the <code>PostInvocationAuthorizationAdvice</code> for the &lt;pre-post-annotation-handling&gt; element.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-post-invocation-advice-parents"><a class="anchor" href="#nsa-post-invocation-advice-parents"></a>Parent Elements of &lt;post-invocation-advice&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-post-invocation-advice-attributes"><a class="anchor" href="#nsa-post-invocation-advice-attributes"></a>&lt;post-invocation-advice&gt; Attributes</h5>
                            <div id="nsa-post-invocation-advice-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-pre-invocation-advice"><a class="anchor" href="#nsa-pre-invocation-advice"></a>2.3.6. &lt;pre-invocation-advice&gt;</h4>
                        <div class="paragraph">
                            <p>Customizes the <code>PreInvocationAuthorizationAdviceVoter</code> with the ref as the <code>PreInvocationAuthorizationAdviceVoter</code> for the &lt;pre-post-annotation-handling&gt; element.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-pre-invocation-advice-parents"><a class="anchor" href="#nsa-pre-invocation-advice-parents"></a>Parent Elements of &lt;pre-invocation-advice&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-pre-invocation-advice-attributes"><a class="anchor" href="#nsa-pre-invocation-advice-attributes"></a>&lt;pre-invocation-advice&gt; Attributes</h5>
                            <div id="nsa-pre-invocation-advice-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-protect-pointcut"><a class="anchor" href="#nsa-protect-pointcut"></a>2.3.7. Securing Methods using</h4>
                        <div class="paragraph">
                            <p><code>&lt;protect-pointcut&gt;</code> Rather than defining security attributes on an individual method or class basis using the <code>@Secured</code> annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the <code>&lt;protect-pointcut&gt;</code> element. You can find an example in the <a href="#ns-protect-pointcut">namespace introduction</a>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-protect-pointcut-parents"><a class="anchor" href="#nsa-protect-pointcut-parents"></a>Parent Elements of &lt;protect-pointcut&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-global-method-security">global-method-security</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-protect-pointcut-attributes"><a class="anchor" href="#nsa-protect-pointcut-attributes"></a>&lt;protect-pointcut&gt; Attributes</h5>
                            <div id="nsa-protect-pointcut-access" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access</strong> Access configuration attributes list that applies to all methods matching the pointcut, e.g. "ROLE_A,ROLE_B"</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-protect-pointcut-expression" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>expression</strong> An AspectJ expression, including the <em>execution</em> keyword. For example, <em>execution(int com.foo.TargetObject.countLength(String))</em> (without the quotes).</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-intercept-methods"><a class="anchor" href="#nsa-intercept-methods"></a>2.3.8. &lt;intercept-methods&gt;</h4>
                        <div class="paragraph">
                            <p>Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean`s methods</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-intercept-methods-attributes"><a class="anchor" href="#nsa-intercept-methods-attributes"></a>&lt;intercept-methods&gt; Attributes</h5>
                            <div id="nsa-intercept-methods-access-decision-manager-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access-decision-manager-ref</strong> Optional AccessDecisionManager bean ID to be used by the created method security interceptor.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-intercept-methods-children"><a class="anchor" href="#nsa-intercept-methods-children"></a>Child Elements of &lt;intercept-methods&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-protect">protect</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-method-security-metadata-source"><a class="anchor" href="#nsa-method-security-metadata-source"></a>2.3.9. &lt;method-security-metadata-source&gt;</h4>
                        <div class="paragraph">
                            <p>Creates a MethodSecurityMetadataSource instance</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-method-security-metadata-source-attributes"><a class="anchor" href="#nsa-method-security-metadata-source-attributes"></a>&lt;method-security-metadata-source&gt; Attributes</h5>
                            <div id="nsa-method-security-metadata-source-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-method-security-metadata-source-use-expressions" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in &lt;intercept-url&gt; elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-method-security-metadata-source-children"><a class="anchor" href="#nsa-method-security-metadata-source-children"></a>Child Elements of &lt;method-security-metadata-source&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-protect">protect</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-protect"><a class="anchor" href="#nsa-protect"></a>2.3.10. &lt;protect&gt;</h4>
                        <div class="paragraph">
                            <p>Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-protect-parents"><a class="anchor" href="#nsa-protect-parents"></a>Parent Elements of &lt;protect&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-intercept-methods">intercept-methods</a></p>
                                    </li>
                                    <li>
                                        <p><a href="#nsa-method-security-metadata-source">method-security-metadata-source</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-protect-attributes"><a class="anchor" href="#nsa-protect-attributes"></a>&lt;protect&gt; Attributes</h5>
                            <div id="nsa-protect-access" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>access</strong> Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-protect-method" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>method</strong> A method name</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="sect2">
                    <h3 id="nsa-ldap"><a class="anchor" href="#nsa-ldap"></a>2.4. LDAP Namespace Options</h3>
                    <div class="paragraph">
                        <p>LDAP is covered in some details in <a href="#ldap">its own chapter</a>. We will expand on that here with some explanation of how the namespace options map to Spring beans. The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project`s API may be useful.</p>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-ldap-server"><a class="anchor" href="#nsa-ldap-server"></a>2.4.1. Defining the LDAP Server using the</h4>
                        <div class="paragraph">
                            <p><code>&lt;ldap-server&gt;</code> Element This element sets up a Spring LDAP <code>ContextSource</code> for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn`t allow anonymous access) for connecting to it. It can also be used to create an embedded server for testing. Details of the syntax for both options are covered in the <a href="#ldap-server">LDAP chapter</a>. The actual <code>ContextSource</code> implementation is <code>DefaultSpringSecurityContextSource</code> which extends Spring LDAP`s <code>LdapContextSource</code> class. The <code>manager-dn</code> and <code>manager-password</code> attributes map to the latter`s <code>userDn</code> and <code>password</code> properties respectively.</p>
                        </div>
                        <div class="paragraph">
                            <p>If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the <code>server-ref</code> attribute. This is actually the bean <code>id</code> of the <code>ContextSource</code> instance, if you want to use it in other traditional Spring beans.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-ldap-server-attributes"><a class="anchor" href="#nsa-ldap-server-attributes"></a>&lt;ldap-server&gt; Attributes</h5>
                            <div id="nsa-ldap-server-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-ldif" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>ldif</strong> Explicitly specifies an ldif file resource to load into an embedded LDAP server. The ldiff is should be a Spring resource pattern (i.e. classpath:init.ldiff). The default is classpath*:*.ldiff</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-manager-dn" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>manager-dn</strong> Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. If omitted, anonymous access will be used.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-manager-password" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>manager-password</strong> The password for the manager DN. This is required if the manager-dn is specified.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-port" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>port</strong> Specifies an IP port number. Used to configure an embedded LDAP server, for example. The default value is 33389.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-root" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>root</strong> Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org"</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-server-url" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>url</strong> Specifies the ldap server URL when not using the embedded LDAP server.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-ldap-authentication-provider"><a class="anchor" href="#nsa-ldap-authentication-provider"></a>2.4.2. &lt;ldap-authentication-provider&gt;</h4>
                        <div class="paragraph">
                            <p>This element is shorthand for the creation of an <code>LdapAuthenticationProvider</code> instance. By default this will be configured with a <code>BindAuthenticator</code> instance and a <code>DefaultAuthoritiesPopulator</code>. As with all namespace authentication providers, it must be included as a child of the <code>authentication-provider</code> element.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-ldap-authentication-provider-parents"><a class="anchor" href="#nsa-ldap-authentication-provider-parents"></a>Parent Elements of &lt;ldap-authentication-provider&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-authentication-manager">authentication-manager</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-ldap-authentication-provider-attributes"><a class="anchor" href="#nsa-ldap-authentication-provider-attributes"></a>&lt;ldap-authentication-provider&gt; Attributes</h5>
                            <div id="nsa-ldap-authentication-provider-group-role-attribute" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-role-attribute</strong> The LDAP attribute name which contains the role name which will be used within Spring Security. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupRoleAttribute</code> property. Defaults to "cn".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-group-search-base" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-search-base</strong> Search base for group membership searches. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupSearchBase</code> constructor argument. Defaults to "" (searching from the root).</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-group-search-filter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-search-filter</strong> Group search filter. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupSearchFilter</code> property. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-role-prefix" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>rolePrefix</code> property. Defaults to "ROLE_". Use the value "none" for no prefix in cases where the default is non-empty.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-server-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>server-ref</strong> The optional server to use. If omitted, and a default LDAP server is registered (using &lt;ldap-server&gt; with no Id), that server will be used.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-user-context-mapper-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-context-mapper-ref</strong> Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user`s directory entry</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-user-details-class" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-details-class</strong> Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-user-dn-pattern" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-dn-pattern</strong> If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. It maps directly to the <code>userDnPatterns</code> property of <code>AbstractLdapAuthenticator</code>. The value is a specific pattern used to build the user`s DN, for example "uid={0},ou=people". The key "{0}" must be present and will be substituted with the username.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-user-search-base" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-search-base</strong> Search base for user searches. Defaults to "". Only used with a <em>user-search-filter</em>.</p>
                                        <div class="paragraph">
                                            <p>If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. The <code>BindAuthenticator</code> will be configured with a <code>FilterBasedLdapUserSearch</code> and the attribute values map directly to the first two arguments of that bean`s constructor. If these attributes aren`t set and no <code>user-dn-pattern</code> has been supplied as an alternative, then the default search values of <code>user-search-filter="(uid={0})"</code> and <code>user-search-base=""</code> will be used.</p>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-authentication-provider-user-search-filter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-search-filter</strong> The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user`s login name.</p>
                                        <div class="paragraph">
                                            <p>If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. The <code>BindAuthenticator</code> will be configured with a <code>FilterBasedLdapUserSearch</code> and the attribute values map directly to the first two arguments of that bean`s constructor. If these attributes aren`t set and no <code>user-dn-pattern</code> has been supplied as an alternative, then the default search values of <code>user-search-filter="(uid={0})"</code> and <code>user-search-base=""</code> will be used.</p>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-ldap-authentication-provider-children"><a class="anchor" href="#nsa-ldap-authentication-provider-children"></a>Child Elements of &lt;ldap-authentication-provider&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-password-compare">password-compare</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-password-compare"><a class="anchor" href="#nsa-password-compare"></a>2.4.3. &lt;password-compare&gt;</h4>
                        <div class="paragraph">
                            <p>This is used as child element to <code>&lt;ldap-provider&gt;</code> and switches the authentication strategy from <code>BindAuthenticator</code> to <code>PasswordComparisonAuthenticator</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-compare-parents"><a class="anchor" href="#nsa-password-compare-parents"></a>Parent Elements of &lt;password-compare&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-ldap-authentication-provider">ldap-authentication-provider</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-compare-attributes"><a class="anchor" href="#nsa-password-compare-attributes"></a>&lt;password-compare&gt; Attributes</h5>
                            <div id="nsa-password-compare-hash" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>hash</strong> Defines the hashing algorithm used on user passwords. We recommend strongly against using MD4, as it is a very weak hashing algorithm.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-password-compare-password-attribute" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>password-attribute</strong> The attribute in the directory which contains the user password. Defaults to "userPassword".</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-password-compare-children"><a class="anchor" href="#nsa-password-compare-children"></a>Child Elements of &lt;password-compare&gt;</h5>
                            <div class="ulist">
                                <ul>
                                    <li>
                                        <p><a href="#nsa-password-encoder">password-encoder</a></p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="sect3">
                        <h4 id="nsa-ldap-user-service"><a class="anchor" href="#nsa-ldap-user-service"></a>2.4.4. &lt;ldap-user-service&gt;</h4>
                        <div class="paragraph">
                            <p>This element configures an LDAP <code>UserDetailsService</code>. The class used is <code>LdapUserDetailsService</code> which is a combination of a <code>FilterBasedLdapUserSearch</code> and a <code>DefaultLdapAuthoritiesPopulator</code>. The attributes it supports have the same usage as in <code>&lt;ldap-provider&gt;</code>.</p>
                        </div>
                        <div class="sect4">
                            <h5 id="nsa-ldap-user-service-attributes"><a class="anchor" href="#nsa-ldap-user-service-attributes"></a>&lt;ldap-user-service&gt; Attributes</h5>
                            <div id="nsa-ldap-user-service-cache-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>cache-ref</strong> Defines a reference to a cache for use with a UserDetailsService.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-group-role-attribute" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-role-attribute</strong> The LDAP attribute name which contains the role name which will be used within Spring Security. Defaults to "cn".</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-group-search-base" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-search-base</strong> Search base for group membership searches. Defaults to "" (searching from the root).</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-group-search-filter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>group-search-filter</strong> Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-id" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-role-prefix" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent storage (e.g. "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-server-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>server-ref</strong> The optional server to use. If omitted, and a default LDAP server is registered (using &lt;ldap-server&gt; with no Id), that server will be used.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-user-context-mapper-ref" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-context-mapper-ref</strong> Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user`s directory entry</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-user-details-class" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-details-class</strong> Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-user-search-base" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-search-base</strong> Search base for user searches. Defaults to "". Only used with a <em>user-search-filter</em>.</p>
                                    </li>
                                </ul>
                            </div>
                            <div id="nsa-ldap-user-service-user-search-filter" class="ulist">
                                <ul>
                                    <li>
                                        <p><strong>user-search-filter</strong> The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user`s login name.</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="sect1">
            <h2 id="appendix-dependencies"><a class="anchor" href="#appendix-dependencies"></a>3. Spring Security Dependencies</h2>
            <div class="sectionbody">
                <div class="paragraph">
                    <p>This appendix provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. We don`t include dependenices that are only used when building or testing Spring Security itself. Nor do we include transitive dependencies which are required by external dependencies.</p>
                </div>
                <div class="paragraph">
                    <p>The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. Note that some of the dependencies listed as"optional" below may still be required for other non-security functionality in a Spring application. Also dependencies listed as "optional" may not actually be marked as such in the project`s Maven pom files if they are used in most applications. They are"optional" only in the sense that you don`t need them unless you are using the specified functionality.</p>
                </div>
                <div class="paragraph">
                    <p>Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately.</p>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-core-2"><a class="anchor" href="#spring-security-core-2"></a>3.1. spring-security-core</h3>
                    <div class="paragraph">
                        <p>The core module must be included in any project using Spring Security.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 3. Core Depenendencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">aopalliance</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.0</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required for method security implementation.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">ehcache</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.6.2</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if the ehcache-based user cache implementation is used (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-aop</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Method security is based on Spring AOP</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-beans</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required for Spring configuration</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-expression</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required for expression-based method security (optional)</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-jdbc</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if using a database to store user data (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-tx</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if using a database to store user data (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">aspectjrt</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.6.10</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if using AspectJ support (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">jsr250-api</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.0</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using JSR-250 method-security annotations (optional).</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-remoting-2"><a class="anchor" href="#spring-security-remoting-2"></a>3.2. spring-security-remoting</h3>
                    <div class="paragraph">
                        <p>This module is typically required in web applications which use the Servlet API.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 4. Remoting Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required for clients which use HTTP remoting support.</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-web-2"><a class="anchor" href="#spring-security-web-2"></a>3.3. spring-security-web</h3>
                    <div class="paragraph">
                        <p>This module is typically required in web applications which use the Servlet API.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 5. Web Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Spring web support classes are used extensively.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-jdbc</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required for JDBC-based persistent remember-me token repository (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-tx</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required by remember-me persistent token repository implementations (optional).</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-ldap-2"><a class="anchor" href="#spring-security-ldap-2"></a>3.4. spring-security-ldap</h3>
                    <div class="paragraph">
                        <p>This module is only required if you are using LDAP authentication.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 6. LDAP Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-ldap-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.3.0</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">LDAP support is based on Spring LDAP.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-tx</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Data exception classes are required.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">apache-ds <span class="footnote">[<a id="_footnoteref_27" class="footnote" href="#_footnote_27" title="View footnote.">27</a>]</span></p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.5.5</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using an embedded LDAP server (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">shared-ldap</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">0.9.15</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using an embedded LDAP server (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">ldapsdk</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">4.1</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Mozilla LdapSDK. Used for decoding LDAP password policy controls if you are using password-policy functionality with OpenLDAP, for example.</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-config-2"><a class="anchor" href="#spring-security-config-2"></a>3.5. spring-security-config</h3>
                    <div class="paragraph">
                        <p>This module is required if you are using Spring Security namespace configuration.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 7. Config Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using any web-related namespace configuration (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-ldap</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using the LDAP namespace options (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-openid</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using OpenID authentication (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">aspectjweaver</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.6.10</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if using the protect-pointcut namespace syntax (optional).</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-acl-2"><a class="anchor" href="#spring-security-acl-2"></a>3.6. spring-security-acl</h3>
                    <div class="paragraph">
                        <p>The ACL module.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 8. ACL Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">ehcache</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.6.2</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if the ehcache-based ACL cache implementation is used (optional if you are using your own implementation).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-jdbc</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using the default JDBC-based AclService (optional if you implement your own).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-tx</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using the default JDBC-based AclService (optional if you implement your own).</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-cas-2"><a class="anchor" href="#spring-security-cas-2"></a>3.7. spring-security-cas</h3>
                    <div class="paragraph">
                        <p>The CAS module provides integration with JA-SIG CAS.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 9. CAS Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">cas-client-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">3.1.12</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">The JA-SIG CAS Client. This is the basis of the Spring Security integration.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">ehcache</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">1.6.2</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using the ehcache-based ticket cache (optional).</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-openid-2"><a class="anchor" href="#spring-security-openid-2"></a>3.8. spring-security-openid</h3>
                    <div class="paragraph">
                        <p>The OpenID module.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 10. OpenID Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">openid4java-nodeps</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">0.9.6</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Spring Security`s OpenID integration uses OpenID4Java.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">httpclient</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">4.1.1</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">openid4java-nodeps depends on HttpClient 4.</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">guice</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">2.0</p>
                                </td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">openid4java-nodeps depends on Guice 2.</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="sect2">
                    <h3 id="spring-security-taglibs"><a class="anchor" href="#spring-security-taglibs"></a>3.9. spring-security-taglibs</h3>
                    <div class="paragraph">
                        <p>Provides Spring Security`s JSP tag implementations.</p>
                    </div>
                    <table class="tableblock frame-all grid-all" style="width:100%; ">
                        <caption class="title">Table 11. Taglib Dependencies</caption>
                        <colgroup>
                            <col style="width:33%;">
                            <col style="width:33%;">
                            <col style="width:33%;">
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="tableblock halign-left valign-top">Dependency</th>
                                <th class="tableblock halign-left valign-top">Version</th>
                                <th class="tableblock halign-left valign-top">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-core</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-web</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top"></td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-security-acl</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using the <code>accesscontrollist</code> tag or <code>hasPermission()</code> expressions with ACLs (optional).</p>
                                </td>
                            </tr>
                            <tr>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">spring-expression</p>
                                </td>
                                <td class="tableblock halign-left valign-top"></td>
                                <td class="tableblock halign-left valign-top">
                                    <p class="tableblock">Required if you are using SPEL expressions in your tag access constraints.</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div id="footnotes">
        <hr>
        <div class="footnote" id="_footnote_1">
            <a href="#_footnoteref_1">1</a>. You can find out more about the use of the <code>ldap-server</code> element in the chapter on <a href="#ldap">LDAP Authentication</a>.
        </div>
        <div class="footnote" id="_footnote_2">
            <a href="#_footnoteref_2">2</a>. See the section on <a href="#request-matching">Request Matching and HttpFirewall</a> in the Web Application Infrastructure chapter for more details on how matches are actually performed.
        </div>
        <div class="footnote" id="_footnote_3">
            <a href="#_footnoteref_3">3</a>. The interpretation of the comma-separated values in the <code>access</code> attribute depends on the implementation of the <a href="#ns-access-manager">AccessDecisionManager</a> which is used. In Spring Security 3.0, the attribute can also be populated with an <a href="#el-access">EL expression</a>.
        </div>
        <div class="footnote" id="_footnote_4">
            <a href="#_footnoteref_4">4</a>. See the chapter on <a href="#anonymous">Anonymous Authentication</a>
        </div>
        <div class="footnote" id="_footnote_5">
            <a href="#_footnoteref_5">5</a>. The use of multiple <code>&lt;http&gt;</code> elements is an important feature, allowing the namespace to simultaneously support both stateful and stateless paths within the same application, for example. The previous syntax, using the attribute <code>filters="none"</code> on an <code>intercept-url</code> element is incompatible with this change and is no longer supported in 3.1.
        </div>
        <div class="footnote" id="_footnote_6">
            <a href="#_footnoteref_6">6</a>. For more details on how channel-processing is implemented, see the Javadoc for <code>ChannelProcessingFilter</code> and related classes.
        </div>
        <div class="footnote" id="_footnote_7">
            <a href="#_footnoteref_7">7</a>. It isn`t possible to create a session once the response has been committed.
        </div>
        <div class="footnote" id="_footnote_8">
            <a href="#_footnoteref_8">8</a>. Note that you`ll need to include the security namespace in your application context XML file in order to use this syntax. The older syntax which used a <code>filter-chain-map</code> is still supported, but is deprecated in favour of the constructor argument injection.
        </div>
        <div class="footnote" id="_footnote_9">
            <a href="#_footnoteref_9">9</a>. Instead of a path pattern, the <code>request-matcher-ref</code> attribute can be used to specify a <code>RequestMatcher</code> instance for more powerful matching
        </div>
        <div class="footnote" id="_footnote_10">
            <a href="#_footnoteref_10">10</a>. You have probably seen this when a browser doesn`t support cookies and the <code>jsessionid</code> parameter is appended to the URL after a semi-colon. However the RFC allows the presence of these parameters in any path segment of the URL
        </div>
        <div class="footnote" id="_footnote_11">
            <a href="#_footnoteref_11">11</a>. The original values will be returned once the request leaves the <code>FilterChainProxy</code>, so will still be available to the application.
        </div>
        <div class="footnote" id="_footnote_12">
            <a href="#_footnoteref_12">12</a>. So, for example, an original request path <code>/secure;hack=1/somefile.html;hack=2</code> will be returned as <code>/secure/somefile.html</code>.
        </div>
        <div class="footnote" id="_footnote_13">
            <a href="#_footnoteref_13">13</a>. We use a forward so that the SecurityContextHolder still contains details of the principal, which may be useful for displaying to the user. In old releases of Spring Security we relied upon the servlet container to handle a 403 error message, which lacked this useful contextual information.
        </div>
        <div class="footnote" id="_footnote_14">
            <a href="#_footnoteref_14">14</a>. In Spring Security 2.0 and earlier, this filter was called <code>HttpSessionContextIntegrationFilter</code> and performed all the work of storing the context was performed by the filter itself. If you were familiar with this class, then most of the configuration options which were available can now be found on`HttpSessionSecurityContextRepository`.
        </div>
        <div class="footnote" id="_footnote_15">
            <a href="#_footnoteref_15">15</a>. For historical reasons, prior to Spring Security 3.0, this filter was called <code>AuthenticationProcessingFilter</code> and the entry point was called <code>AuthenticationProcessingFilterEntryPoint</code>. Since the framework now supports many different forms of authentication, they have both been given more specific names in 3.0.
        </div>
        <div class="footnote" id="_footnote_16">
            <a href="#_footnoteref_16">16</a>. In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins. The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible.
        </div>
        <div class="footnote" id="_footnote_17">
            <a href="#_footnoteref_17">17</a>. It is possible to encode the password in the format HEX( MD5(username:realm:password) ) provided the <code>DigestAuthenticationFilter.passwordAlreadyEncoded</code> is set to <code>true</code>. However, other password encodings will not work with digest authentication.
        </div>
        <div class="footnote" id="_footnote_18">
            <a href="#_footnoteref_18">18</a>. Essentially, the username is not included in the cookie, to prevent exposing a valid login name unecessarily. There is a discussion on this in the comments section of this article.
        </div>
        <div class="footnote" id="_footnote_19">
            <a href="#_footnoteref_19">19</a>. Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by`SessionManagementFilter`, as the filter will not be invoked during the authenticating request. Session-management functionality has to be handled separately in these cases.
        </div>
        <div class="footnote" id="_footnote_20">
            <a href="#_footnoteref_20">20</a>. The use of the <code>key</code> property should not be regarded as providing any real security here. It is merely a book-keeping exercise. If you are sharing a <code>ProviderManager</code> which contains an <code>AnonymousAuthenticationProvider</code> in a scenario where it is possible for an authenticating client to construct the <code>Authentication</code> object (such as with RMI invocations), then a malicious client could submit an <code>AnonymousAuthenticationToken</code> which it had created itself (with chosen username and authority list). If the <code>key</code> is guessable or can be found out, then the token would be accepted by the anonymous provider. This isn`t a problem with normal usage but if you are using RMI you would be best to use a customized <code>ProviderManager</code> which omits the anonymous provider rather than sharing the one you use for your HTTP authentication mechanisms.
        </div>
        <div class="footnote" id="_footnote_21">
            <a href="#_footnoteref_21">21</a>. Note that this is different from the default configuration of the underlying <code>DefaultLdapAuthoritiesPopulator</code> which uses <code>member={0}</code>.
        </div>
        <div class="footnote" id="_footnote_22">
            <a href="#_footnoteref_22">22</a>. It is also possible to obtain the server`s IP address using a DNS lookup. This is not currently supported, but hopefully will be in a future version.
        </div>
        <div class="footnote" id="_footnote_23">
            <a href="#_footnoteref_23">23</a>. The legacy options from Spring Security 2.0 are also supported, but discouraged.
        </div>
        <div class="footnote" id="_footnote_24">
            <a href="#_footnoteref_24">24</a>. See the <a href="#ns-web-xml">introductory chapter</a> for how to set up the mapping from your <code>web.xml</code>
        </div>
        <div class="footnote" id="_footnote_25">
            <a href="#_footnoteref_25">25</a>. This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). The class <code>DefaultLoginPageGeneratingFilter</code> is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required.
        </div>
        <div class="footnote" id="_footnote_26">
            <a href="#_footnoteref_26">26</a>. This doesn`t affect the use of <code>PersistentTokenBasedRememberMeServices</code>, where the tokens are stored on the server side.
        </div>
        <div class="footnote" id="_footnote_27">
            <a href="#_footnoteref_27">27</a>. The modules <code>apacheds-core</code>, <code>apacheds-core-entry</code>, <code>apacheds-protocol-shared</code>, <code>apacheds-protocol-ldap</code> and <code>apacheds-server-jndi</code> are required.
        </div>
    </div>
    <div id="footer">
        <div id="footer-text">
            Version 3.2.9.RELEASE
            <br> Last updated 2015-10-30 11:56:20 PDT
        </div>
    </div>
    <script src="http://cdn.bootcss.com/prettify/r298/prettify.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', prettyPrint)
    </script>
</body>

</html>
